在ASP.NET Core中,可以使用CookieAuthenticationOptions
类中的ExpireTimeSpan
属性来设置cookie的过期时间。以下是一个具体的示例:
Startup.cs
文件中的ConfigureServices
方法中添加以下代码:services.Configure(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(30); // 设置cookie的过期时间为30分钟
});
Configure
方法中添加以下代码来启用cookie身份验证:app.UseAuthentication();
在需要验证的控制器或操作方法上添加[Authorize]
特性,以确保只有经过身份验证的用户才能访问它们。
如果需要在登录时设置cookie的过期时间,可以使用HttpContext.SignInAsync
方法的AuthenticationProperties
参数来设置过期时间。以下是一个示例:
[HttpPost]
public async Task Login(LoginViewModel model)
{
// 验证用户登录信息
var claims = new List
{
new Claim(ClaimTypes.Name, model.Username),
// ...
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(30) // 设置过期时间为30分钟后
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
return RedirectToAction("Index", "Home");
}
在上述示例中,ExpiresUtc
属性用于设置cookie的过期时间。