HTTP模块会话未在无扩展页面中设置

时间:2010-10-26 12:45:09

标签: c# asp.net httpmodule

我有一个我编写的HTTP模块需要访问会话。我做了以下事情:

  • 模块已在web.config中注册
  • 模块将我的方法调用附加到PostAcquireRequestState事件
  • 模块实现IRequiresSessionState

但是,当我的页面没有扩展名时(例如,当htp://www.mywebsite.com时)会话不可用且我的代码失败。如果页面确实有一个aspx扩展名,那么一切正常。

3 个答案:

答案 0 :(得分:0)

您需要拥有一个由ASP.NET处理的项目,以使您的模块成为请求生命周期的一部分。提供像index.html这样的页面将无法实现这一目标。 ASPX页面将会。

答案 1 :(得分:0)

来自以下线程的代码可以解决问题(1):

public class Module : IHttpModule, IRequiresSessionState
{
    public void Dispose()
    {
    }

    void OnPostMapRequestHandler(object source, EventArgs e)
    {
        HttpApplication app = (HttpApplication)source;

        if (app.Context.Handler is IReadOnlySessionState || app.Context.Handler is IRequiresSessionState)
            return;

        app.Context.Handler = new MyHttpHandler(app.Context.Handler);
    }

    void OnPostAcquireRequestState(object source, EventArgs e)
    {
        HttpApplication app = (HttpApplication)source;

        MyHttpHandler resourceHttpHandler = HttpContext.Current.Handler as MyHttpHandler;

        if (resourceHttpHandler != null)
            HttpContext.Current.Handler = resourceHttpHandler.OriginalHandler;
    }

    public void Init(HttpApplication httpApp)
    {
        httpApp.PostAcquireRequestState += new EventHandler(OnPostAcquireRequestState);
        httpApp.PostMapRequestHandler += new EventHandler(OnPostMapRequestHandler);
    }

    public class MyHttpHandler : IHttpHandler, IRequiresSessionState
    {
        internal readonly IHttpHandler OriginalHandler;

        public void ProcessRequest(HttpContext context)
        {
            throw new InvalidOperationException("MyHttpHandler cannot process requests.");
        }

        public MyHttpHandler(IHttpHandler originalHandler)
        {
            OriginalHandler = originalHandler;
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}

答案 2 :(得分:-2)