【问题标题】:Session returns null in site.master page会话在 site.master 页面中返回 null
【发布时间】:2017-09-08 07:16:33
【问题描述】:

我试图将一个值从 asp.net 登录控件传递到一个完全不同的 site.master 页面。这是我的 login.aspx.cs 页面 -

    protected void LoginUser_OnAuthenticate(object sender, AuthenticateEventArgs e)
    {
        Session["username"] = LoginUser.UserName;
        Security.AuthenticateUser(LoginUser.UserName, LoginUser.Password, LoginUser.RememberMeSet);
    }

这部分代码从 login.aspx 页面接收值 -

<asp:Login ID="LoginUser" runat="server" EnableViewState="false" RenderOuterTable="false" OnAuthenticate="LoginUser_OnAuthenticate">
    <div class="form-group">
         <label>Username</label>
         <asp:TextBox ID="UserName" runat="server" AutoCompleteType="None" CssClass="textEntry ltr-dir"></asp:TextBox>
    </div>
    <div class="form-group">
         <label>Password</label>
         <asp:TextBox ID="Password" runat="server" CssClass="passwordEntry ltr-dir" TextMode="Password"></asp:TextBox>
   </div>
</asp:Login>

这是我的 site.master 页面 -

var username = Session["username"].ToString();

var settings = ConfigurationManager.ConnectionStrings["BlogEngine"].ConnectionString;
SqlConnection conn = new SqlConnection(settings);

每当我调试时,Var 用户名都会得到一个空值。而在login.aspx.cs 页面中,它将用户名的值传递到会话中。

请问我该如何解决?

注意:Security.AuthenticateUer() 方法 -

public static bool AuthenticateUser(string username, string password, bool rememberMe)
    {
        string un = (username ?? string.Empty).Trim();
        //string pw = (password ?? string.Empty).Trim();

        if (!string.IsNullOrWhiteSpace(un))
        {
            var user = Membership.GetUser(un);
            string res = Convert.ToString(user);
            bool isValidated = Membership.ValidateUser(res, DEFAULT_PASSWORD);
            if (isValidated)
            {
                if (BlogConfig.SingleSignOn)
                {
                    FormsAuthentication.SetAuthCookie(un, rememberMe);
                    return true;
                }

                HttpContext context = HttpContext.Current;
                DateTime expirationDate = DateTime.Now.Add(FormsAuthentication.Timeout);

                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1,
                    un,
                    DateTime.Now,
                    expirationDate,
                    rememberMe,
                    $"{SecurityValidationKey}{AUTH_TKT_USERDATA_DELIMITER}{Blog.CurrentInstance.Id}",
                    FormsAuthentication.FormsCookiePath
                );

                string encryptedTicket = FormsAuthentication.Encrypt(ticket);

                // setting a custom cookie name based on the current blog instance.
                // if !rememberMe, set expires to DateTime.MinValue which makes the
                // cookie a browser-session cookie expiring when the browser is closed.
                System.Web.HttpCookie cookie = new System.Web.HttpCookie(FormsAuthCookieName, encryptedTicket);
                cookie.Expires = rememberMe ? expirationDate : DateTime.MinValue;
                cookie.HttpOnly = true;
                context.Response.Cookies.Set(cookie);

                string returnUrl = context.Request.QueryString["returnUrl"];
                Console.WriteLine("Redirect To This URL :" + returnUrl);

                // ignore Return URLs not beginning with a forward slash, such as remote sites.
                if (string.IsNullOrWhiteSpace(returnUrl) || !returnUrl.StartsWith("/"))
                    returnUrl = null;

                if (!string.IsNullOrWhiteSpace(returnUrl))
                {
                    context.Response.Redirect(returnUrl);
                }
                else
                {
                    if (IsReportUser(un))
                    {
                        var reportPage = "";
                        context.Response.Redirect(reportPage);
                    };

                     context.Response.Redirect(Utils.RelativeWebRoot); 
                }

                return true;
            }
        }
        return false;
    }

【问题讨论】:

  • login.aspx 是否使用相同的母版页?如果是这样,Session["username"] 将为空,同时在 login.aspx 登录。
  • @Win,login.aspx 使用不同的母版页 - account.master。一旦 login.aspx.cs 对用户进行身份验证,它会将用户登录到 site.master。
  • 能否展示Security.AuthenticateUser的代码?
  • @Win - 检查我更新的帖子

标签: c# asp.net blogengine.net


【解决方案1】:

由于您使用的是 FormAuthentication,用户名是真实存储在 Principle 对象中的。你可以像这样检索用户名 -

var username = User.Identity.Name;

【讨论】:

  • 是这个 System.Web 的命名空间吗?因为我不断得到名称 'Üser' 在当前上下文中不存在并且我已经导入了 System.Web
  • 好的,我使用了 var username = HttpContext.Current.User.Identity.Name。让我测试一下,然后回复你。
猜你喜欢
  • 2014-05-27
  • 2013-02-07
  • 2016-09-23
  • 2015-10-11
  • 2019-06-08
  • 2017-07-03
  • 1970-01-01
  • 2021-05-08
  • 1970-01-01
相关资源
最近更新 更多