.net core 有自己的cookie机制,不需要单独写js进行实现
statup.cs 文件中找到Configure方法
//Cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookie",// 验证方案名
AutomaticAuthenticate = true,
ExpireTimeSpan = TimeSpan.FromSeconds(30)//cookie过期时间
AutomaticChallenge = true,
AccessDeniedPath = new PathString("/System/Error") //访问拒绝跳到error页面
});
页面选择登录状态保持,在登录成功之后设置cookie
if (model.LoginState)
{
// cookie
var identity = new ClaimsIdentity("Forms");
identity.AddClaim(new Claim(ClaimTypes.Sid, model.LoginId));
identity.AddClaim(new Claim(ClaimTypes.Rsa, model.Password));
identity.AddClaim(new Claim(ClaimTypes.Name, Convert.ToString(model.LoginState)));
var principal = new ClaimsPrincipal(identity);
HttpContext.Authentication.SignInAsync("Cookie", principal, new AuthenticationProperties { IsPersistent = true });//是否解析
}
解析cookie
// cookie
string loginId = CommonConstant.S_SPACE;
string password = CommonConstant.S_SPACE;
bool loginState = false;
if (null != User.FindFirst(ClaimTypes.Sid)
&& null != User.FindFirst(ClaimTypes.Rsa)
&& null != User.FindFirst(ClaimTypes.Name))
{
loginId = User.FindFirst(ClaimTypes.Sid).Value;
password = User.FindFirst(ClaimTypes.Rsa).Value;
loginState = Convert.ToBoolean(User.FindFirst(ClaimTypes.Name).Value);// ログイン状態
}
如果statup.cs文件中设置path
//Cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookie",
AutomaticAuthenticate = true,
ExpireTimeSpan = TimeSpan.FromSeconds(30)//cookie过期时间
LoginPath = "/account/login" // 登录页
});
后台login动作加入注解[AllowAnonymous],在保持状态之后页面可以直接跳转到login动作中
logout时HttpContext.Authentication.SignOutAsync("member"); // Startup.cs中配置的验证方案名
.NET CORE cookie
猜你喜欢
转载自blog.csdn.net/u012601647/article/details/68579663
今日推荐
周排行