【问题标题】:ASP.NET Session variable becomes null?ASP.NET 会话变量变为空?
【发布时间】:2014-04-17 17:12:46
【问题描述】:

我的解决方案资源管理器(如果有帮助): http://i.stack.imgur.com/BdhDz.png

当我单击帐户按钮(带有指向 account.aspx 的 href)时,它会将我重定向到 login.aspx,因为未经授权。

在我的 login.aspx.cs(点击登录后),我有

Session["hi"] = "hello";
HttpCookie cookie = new HttpCookie("username");
cookie.Value = UName.Text;
Response.Cookies.Add(cookie);
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(UName.Text, false);

在我的 account.aspx.cs 上

if (Session["hi"] != null)
{
    Literal1.Text = Session["hi"].ToString();
    Literal1.Text += "<br><br><br>";
}

为什么什么都不显示?我尝试了各种方法来显示这个会话,没有工作, 由于某种原因 Session["hi"] 为空。

【问题讨论】:

  • 你确定accountlogin 中的代码被处理后被调用吗?你可以在两个地方都放断点吗?
  • 既然您使用的是 FormsAuthentication,为什么还要创建 username cookie?将内容发布到~/LoggedIn/web.config
  • '' 配置>'
  • @Mikiku 把&lt;authentication&gt;的内容贴在~/web.config里面
  • &lt;allow users="Role"/&gt; 不见了?

标签: c# asp.net session-variables


【解决方案1】:

根据您上次的评论,您需要将AuthenticationSection.Mode Property 设置为mode="Forms"

默认情况下,它是窗口模式。

<authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" 
     timeout="2880" 
     cookieless="UseCookies" />
</authentication>

如何创建主体对象

一旦通过身份验证的用户被请求页面,您需要从 cookie 中检索身份验证票,并创建一个 Principal 对象。

Global.asax.cs

void Application_AuthenticateRequest(object sender, EventArgs e)
{
   HttpCookie decryptedCookie = 
      Context.Request.Cookies[FormsAuthentication.FormsCookieName];

   FormsAuthenticationTicket ticket = 
      FormsAuthentication.Decrypt(decryptedCookie.Value);

   var identity = new GenericIdentity(ticket.Name);
   var principal = new GenericPrincipal(identity, null);

   HttpContext.Current.User = principal;
   Thread.CurrentPrincipal =HttpContext.Current.User;
}

用法

if (User.Identity.IsAuthenticated)
{

}

【讨论】:

  • 但我有
  • 看起来您没有在 AuthenticateRequest 上创建 IPrincipal 对象。我更新了我的答案。
  • ehhh,我的第一个任务看起来很辛苦;d 谢谢
猜你喜欢
  • 2015-03-11
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-09
  • 2014-03-24
相关资源
最近更新 更多