在C#中访问上下文会话变量 [英] Accessing context session variables in c#

查看:92
本文介绍了在C#中访问上下文会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET应用程序和扩展IHttpModule的dll.我已使用以下方法通过

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";
        }
}

并且在我的asp.net Default.aspx页面中,我使用代码来检索值为

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();
    }
}

我收到的错误响应为

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.

推荐答案

为什么需要使用Context而不是直接使用Session?从代码中,我只能假定您将在Session中设置一个值,然后在页面加载时读取该值.您可以执行以下操作,而不是执行类似的操作:

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. 添加一个全局应用程序类,右键单击您的项目,单击添加">新建项目",选择全局应用程序类",然后在该文件上,插入以下代码以初始化值

  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";
}

  • 在Page_Load上,您可以通过以下方式访问:

  • On the Page_Load, you can access by:

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

  • 希望这项帮助.

    这篇关于在C#中访问上下文会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆