引用
Microsoft.AspNetCore.Authentication.Cookies
Startup.cs
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)//注册cookie
.AddCookie(options =>
{
options.LoginPath = "/Home/Login";
options.LogoutPath = "/Home/LogOut";
options.Cookie.HttpOnly = true;
options.Cookie.Path = "/";
options.Cookie.Name = "mycookie";
options.Cookie.Expiration =TimeSpan.FromDays(7);
options.SlidingExpiration = true;
});
app.UseAuthentication();
//登录提交
var user = new ClaimsPrincipal(
new ClaimsIdentity(new[]
{
new Claim("UserID", l.CenterManage_Admin_PID.ToString()),
new Claim("AdminName", l.AdminName),
new Claim("AdminUser", l.AdminUser),
},
CookieAuthenticationDefaults.AuthenticationScheme));
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user, new Microsoft.AspNetCore.Authentication.AuthenticationProperties
{
IsPersistent = true,
});
//退出登录
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login", "Home");
//拦截器BaseController
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//如果HttpContext.User.Identity.IsAuthenticated为true,
//或者HttpContext.User.Claims.Count()大于0表示用户已经登录
if (!HttpContext.User.Identity.IsAuthenticated)
{
//HttpContext.Response.Redirect("/Home/Index");
filterContext.Result =
new RedirectToRouteResult(
new RouteValueDictionary { { "controller", "Home" }, { "action", "Index" } });
}
else
{
}
base.OnActionExecuting(filterContext);
}
//获取cookie的值
/// <summary>
/// 获取Cookie
/// </summary>
/// <param name="http">HttpContext.User.Claims</param>
/// <param name="TypeName">名称</param>
/// <returns></returns>
public static string GetCookieToValue(IEnumerable<Claim> http, string TypeName)
{
var result = (from c in http
where c.Type == TypeName
select c.Value).FirstOrDefault();
return result;
}
控制器调用
WebCookie.GetCookieToValue(HttpContext.User.Claims, "AdminName");