net core2.0 cookie

引用
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");

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值