ASP.NET登录记住用户名

时间:2023-03-09 19:22:07
ASP.NET登录记住用户名

案例如下:

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);
                }
            }
        }