Session is always null when redirect to another page? c#

北慕城南 提交于 2021-02-08 03:37:05

问题


I tried to add session and then i accessed on another page after redirect this always show null

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

here on another page i am accessing like this

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

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

I tried

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

and also

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

and Admin page where assigning value to session

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

and web.config file

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

but still facing same session is null


回答1:


Based on this answer which basically refers to this msdn article about SessionID, you might need to initialise your session object on Session_Start:

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

This is required when session state is stored in a cookie, which you currently use based on your web.config. The reason is that ASP.NET does not save session up until its first usage and as a result a new SessionID is generated with each new page request which is happening when you Response.Redirect to another page.



来源:https://stackoverflow.com/questions/44299680/session-is-always-null-when-redirect-to-another-page-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!