ASP.NET登录记住用户名

案例如下:

1:首先在登录的控制器中定义一个全局变量

        public const string LonginName = "sessName";

2:在登陆的方法中

  public ActionResult Login(string userNameOrEmailAddress = "", string returnUrl = "", string successMessage = "")
        {
            if (string.IsNullOrWhiteSpace(returnUrl))
                returnUrl = Url.Action("Index", "Application");

            ViewBag.ReturnUrl = returnUrl == "/" ? "" : returnUrl;
            ViewBag.IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled;

var model = new LoginFormViewModel();           

    HttpCookie remCookie = HttpContext.Request.Cookies[LonginName];
 
            if (remCookie != null)
            {
                model.RemberName = remCookie.Value;
            }
            else
            {
                model.RemberName = "";
            }

            model.TenancyName = _tenancyNameFinder.GetCurrentTenancyNameOrNull();
            model.IsSelfRegistrationEnabled = true;
            model.SuccessMessage = successMessage;
            model.UserNameOrEmailAddress = userNameOrEmailAddress;
            return View(model);
        }

3:在登陆成功后记录Cookie

        /// <summary>
        /// 注入登录信息到Cookie
        /// </summary>
        /// <returns></returns>
        private async Task SignInAsync(ClaimsIdentity identity = null, bool rememberMe = false)
        {

            HttpCookie remCookie = HttpContext.Request.Cookies[LonginName];
            // 登录成功后记录Session
            if (rememberMe)
            {
                HttpCookie cook = new HttpCookie(LonginName);
                cook.Expires.AddDays(7);
                cook.Value = identity.Name;
                HttpContext.Response.SetCookie(cook);
            }
            else
            {
                if (remCookie != null)
                {
                    remCookie.Value = null;
                    HttpContext.Response.SetCookie(remCookie);
                }
            }
        }

 

posted @ 2017-04-27 09:37  begrateful  阅读(1083)  评论(0编辑  收藏  举报