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

     

  • 相关阅读:
    解决安装postgresql安装报An error occurred executing the Microsoft C++ runtime installer.问题
    使用U盘为龙芯笔记本安装操作系统
    年终复盘与展望(2017年)
    年终复盘与展望(2016年)
    Spark log4j 配置
    R语言码农的Scala学习心得
    在集群上运行Spark应用
    通过 Spark R 操作 Hive
    CentOS 6.7 hadoop free版本Spark 1.6安装与使用
    OS X Maven 安装与使用简介
  • 原文地址:https://www.cnblogs.com/wendj/p/6772613.html
Copyright © 2011-2022 走看看