开发者

HttpContextBase: Session is null

开发者 https://www.devze.com 2023-03-07 13:36 出处:网络
I use Windor Castle to wrap the HttpContext into a HttpContextWrapper via a factory method. container.Register(

I use Windor Castle to wrap the HttpContext into a HttpContextWrapper via a factory method.

container.Register(
    Component.For<HttpContextBase>()
        .LifeStyle.PerWebRequest
        .UsingFactoryMethod(() => new HttpContextWrapper(HttpContext.Current)));

I have a class called SessionStorage which accesses HttpContext.Current.Session. I register it this way:

container开发者_JS百科.Register(
    Component.For<ISessionStorage>()
    .LifeStyle.PerWebRequest
    .ImplementedBy<HttpSessionStorage>());

The HttpSessionStorage class:

public class HttpSessionStorage : ISessionStorage
{
    public HttpContextBase httpContext { get; set; }

    public void Remove(string key)
    {
        httpContext.Session.Remove(key);        
    }

    public T Get<T>(string key)
    {
        return (T)httpContext.Session[key];
    }

    public void Set<T>(string key, T value)
    {
        httpContext.Session[key] = value;
    }
}

When I use it this way, then in about 40% of the cases the Session property is null and only if the requests are at a very high rate.

The strange thing is that if I use HttpContext.Current instead of httpContext, it works in all cases.

public class HttpSessionStorage : ISessionStorage
{
    public HttpContextBase httpContext { get; set; }

    public void Remove(string key)
    {
        HttpContext.Current.Session.Remove(key);        
    }

    public T Get<T>(string key)
    {
        return (T)HttpContext.Current.Session[key];
    }

    public void Set<T>(string key, T value)
    {
        HttpContext.Current.Session[key] = value;
    }
}

It has something to do with Windsor Castle but I can't find the problem. I registered everything I can as PerWebRequest (except a NHibernate session factory).

Does someone have an idea what else I could check?

Lg

warappa


OK, it wasn't due to inproper Castle Windsor registration but something simpler: I accessed Session at a time when it's not garanteed to be fully initialized - dummy me!

My solution was to move the Session accessing code from Application_BeginRequest to Application_AcquireRequestState like pointed out here.

Note:
Maybe this code should be moved into a base controller - in OnAuthorization (edit: it works!).


I had similar problems a while back, maybe the answers to my question can help you: ASP.NET MVC & Windsor.Castle: working with HttpContext-dependent services

0

精彩评论

暂无评论...
验证码 换一张
取 消