会话在IHttpModule中不可用 [英] Session not available in IHttpModule

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

问题描述

在我的程序中,我试图在IHttpModule中使用会话变量.这是我的代码.这在VS 2010开发服务器中运行正常.但是当我尝试在IIS7中调试时,它显示异常 System.Web.HttpException:在此上下文中会话状态不可用那么,为什么会话在IIS 7中不可用,但在开发服务器中不可用.

In my program I'm trying to use session variable in IHttpModule. Here is my code. This is working fine in VS 2010 development server. But when I try to debug in IIS7 it shows exception System.Web.HttpException: Session state is not available in this context So why session not available in IIS 7 but in development server.

using System;
using System.Web;

public class Globalizer : IHttpModule
{    
  public void Init(HttpApplication context)
  {
    context.AcquireRequestState += new EventHandler(setLanguage);
  }

  public void Dispose(){}

  public void setLanguage(Object sender, EventArgs i_eventArgs)
  {
    HttpApplication http_application = sender as HttpApplication;     
    http_application.Session["language"] = "test";

  }
}

推荐答案

找到了原因.

如果是因为 AcquireRequestState 触发了所有文件,例如CSS,JS,图像.这些文件没有会话.

If is because AcquireRequestState trigger for the all files such as CSS, JS, images. those files are not having session.

解决方案:似乎有一种方法可以避免为所有请求调用 IHttpModule .修改此答案 JS,图像和CSS被HTTPModule拦截

solution: Seems there is a way to avoid calling IHttpModule for all the request. ckeck this answer JS,Images and CSS getting intercepted by HTTPModule.

但这对我不起作用.因此,我使用 HttpContext.Current.Session 而不是 HttpApplication.Session ,并在每次保存到会话之前都检查Session是否为空.

But it didn't work for me. So I uses HttpContext.Current.Session instead of HttpApplication.Session and every time it checks if Session is null before save to session.

如果有人知道,如何避免对 .aspx 以外的文件调用 IHttpModule ,请在此处提供帮助.

If some one knows, How to avoid calling IHttpModule for files other than .aspx Please help here.

这是最终代码

using System;
using System.Web;

public class Globalizer : IHttpModule
{    
  public void Init(HttpApplication context)
  {
    context.AcquireRequestState += new EventHandler(setLanguage);
  }

  public void Dispose(){}

  public void setLanguage(Object sender, EventArgs i_eventArgs)
  {
    if(HttpContext.Current.Session != null){
      HttpContext.Current.Session["language"] = "test";
    }

  }
}

另一种方法是仅在请求到达 .aspx 文件

One other way is only use session if request comes to a .aspx file

HttpApplication http_application = sender as HttpApplication; 
HttpContext context = http_application.Context;
if(Path.GetExtension(context.Request.PhysicalPath) == ".aspx")
{
 HttpContext.Current.Session["language"] = "test";
 http_application.Session["language2"] = "test2";
} 

这篇关于会话在IHttpModule中不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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