开发者

ASP.NET MVC HttpContext.Session object

I have a question. I've built custom class in my project that contains开发者_高级运维 public static property ctx and assingn HttpContext.Current object to it. In runtime that property seem to reference HttpContext object, but ctx.Session class is null. When i debug my app the left side of an expression (ctx) is not exactly the same as right side (HttpContext.Current). why this is happening?

Grettings


HttpContext.Current is a singleton only for that request. By assigning the HttpContext.Current to a static variable you would be sharing this HttpContext.Current to an entire scope, which may not be right.

Session is a per user object while, static is an application wide object. Use static wisely.


What I would do would be something like this.

1- a static class (ex: ContextFactory) which provides current httpcontext. If it has HttpContext.Current, then is provides that value, if not then it provides an assigned context. In your case, new Mock<HttpContextBase>();

public static class ContextFactory
{
    private static HttpContextBase current = null;

    public static HttpContextBase Current
    {
        get { return current ?? HttpContext.Current; }
        set { current = value; }
    }
}

2- Then I alter the code UserSess to

public static class UserSess 
{
    public static UserID
    {
        get { return ContextFactory.Current.Session["UserID"]; }
        set { ContextFactory.Current.Session["UserID"] = value; } 
    }
   //... 
}

sincerely

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜