c# - 重定向到另一个页面时 session 始终为空? C#

标签 c# asp.net session

我尝试添加 session ,然后在重定向后在另一个页面上访问,这始终显示为空

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" %>

和为 session 赋值的管理页面

 <%@ 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>

但还是面临same session is null

最佳答案

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

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

当 session 状态存储在您当前基于 web.config 使用的 cookie 中时,这是必需的。原因是 ASP.NET 在第一次使用之前不会保存 session ,因此当您 Response.Redirect 到另一个页面。

关于c# - 重定向到另一个页面时 session 始终为空? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44299680/

相关文章:

c# - `AsyncLocal` 是否也做 `ThreadLocal` 做的事情?

c# - 两个线程 - Console.out 的两个流

c# - 如何从同一解决方案中的第二个项目的 Controller 派生

c# - 3rd party是302重定向到我的网站,如何停止?

php - 在 PHP 共享主机上保护数据库和 session 数据

php - 无法在服务器中设置 session ,在本地主机上工作

php - PDO 将 session 值插入数据库

c# - ObservableCollection CollectionChanged 事件似乎没有触发——为什么?

c# - 加载第二页时如何更改母版页的CSS样式表

c# - 将 asp.net 上传到主机 (GoDaddy)