Accessing context session variables in c#

二次信任 提交于 2019-12-25 02:50:18

问题


I have an ASP.NET application and dll which extends IHttpModule. I have used the below method to save the session variables in httpcontext through

public class Handler : IHttpModule,IRequiresSessionState
  {

 public void Init(HttpApplication httpApp)
 {
    httpApp.PreRequestHandlerExecute += new EventHandler(PreRequestHandlerExecute);
}

 public void PreRequestHandlerExecute(object sender, EventArgs e)
        {
                var context = ((HttpApplication)sender).Context;
                context.Session["myvariable"] = "Gowtham";
        }
}

and in my asp.net Default.aspx page I have used code to retrive value as

   public partial class _Default : System.Web.UI.Page, IRequiresSessionState
    {
    protected void Page_Load(object sender, EventArgs e)
        {
      String token = Context.Session["myvariable"].ToString();
    }
}

I am getting error response as

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

In order to ensure whether the variables store in session I have crossed check by following method in class handler after storing the value in session as

  string ss = context.Session["myvariable"].ToString();

it well executed and retrieved the value from session.


回答1:


Why do you need to use Context and not Session directly? From the code I can only assume that you are going to set a value in the Session, and then read the value on page load. Rather than you do something like that, you can do this:

  1. Add a Global Application Class, Right click on your project, Add > New Item, choose Global Application Class, and on that file, insert the following code to initialize the value

    protected void Session_Start(object sender, EventArgs e)
    {
        Session["myvariable"] = "Gowtham";
    }
    
  2. On the Page_Load, you can access by:

    if ( Session["myvariable"] != null ) {
        String token = Context.Session["myvariable"].ToString();
    }
    

Hope this help..




回答2:


use System.Web.HttpContext.Current.Session["myvariable"] in both parts



来源:https://stackoverflow.com/questions/15540455/accessing-context-session-variables-in-c-sharp

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