【问题标题】:Session is always null when redirect to another page? c#重定向到另一个页面时会话始终为空? C#
【发布时间】:2017-11-02 03:19:36
【问题描述】:

我尝试添加会话,然后我在重定向后访问另一个页面,这总是显示为空

Session.Add("pUser_Name", ds_1.Tables[0].Rows[0]["User_Name"].ToString());
HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.Redirect("DashBoard.aspx", false);

在我正在访问的另一个页面上

protected void Page_Load(object sender, EventArgs e)
{
     if (Session["pUser_Name"] == null)  ////here is error NULL
     {

         Response.Redirect("Admin.aspx");
     }
 }

我试过了

protected override void OnInit(EventArgs e)
{
    if (Session["pUser_Name"] == null)
    {
        Response.Redirect("Admin.aspx");
    }
    base.OnInit(e);
}

还有

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DashBoard.aspx.cs" Inherits="SC.DashBoard" EnableTheming="true"
Theme="Theme1" EnableSessionState="True" %>

和为会话分配值的管理页面

 <%@ Page Language="C#" AutoEventWireup="true" EnableSessionState="True" CodeBehind="Admin.aspx.cs" Inherits="SC.Admin" %>

和 web.config 文件

<system.web>
   <compilation debug="true" targetFramework="4.0"/>
   <sessionState timeout="12000"/>
</system.web>

但仍然面临同一个会话是空的

【问题讨论】:

  • 只是为了尝试而不是Session.Add 使用HttpContext.Current.Session.Add 并像HttpContext.Current.Session["pUser_Name"] 一样访问
  • 同样的问题仍未解决
  • 更新面板也无法解决问题..
  • 明确一点,什么是空?是 Session 还是 Session["pUser_name"]?
  • 请注意,如果您的页面是通过从外部网关或应用程序返回和回调加载的,则它具有不同的请求者和不同的会话 ID

标签: c# asp.net session


【解决方案1】:

基于这个answer 基本上是指这个msdn article 关于SessionID,你可能需要在Session_Start上初始化你的会话对象:

protected void Session_Start(Object sender, EventArgs e) 
{
    Session["init"] = 0;
}

当会话状态存储在 cookie 中时,这是必需的,您当前根据 web.config 使用该 cookie。原因是 ASP.NET 在第一次使用之前不会保存会话,因此当您 Response.Redirect 到另一个页面时,每个 new 页面请求都会生成一个新的 SessionID。

【讨论】:

    猜你喜欢
    • 2020-04-12
    • 1970-01-01
    • 2012-10-12
    • 2013-11-28
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多