zoukankan      html  css  js  c++  java
  • 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);
                    }
                }
            }

     

  • 相关阅读:
    【转】什么是5G?居然有人用漫画把它讲得如此接地气!
    【转】Centos下编译升级安装Boost
    【转】SSH穿越跳板机:一条命令跨越跳板机直接登陆远程计算机
    部署JupyterLab和pyalgotrade搭建web策略回测环境
    [转]Linux中python3.6+ipython+Jupyter Notebook环境
    环境命令备忘
    [转]微软商店 打开就显示无法加载该页面 代码0x80131500?
    [转]Centos 7 安装部署 GitLab 服务器
    [转]本文采用all-in-one(一体化的)安装OpenShift
    [转]Linux编译和安装boost库
  • 原文地址:https://www.cnblogs.com/wendj/p/6772613.html
Copyright © 2011-2022 走看看