HttpContext.Current accessed in static classes

2019-04-19 12:33发布

Can I call HttpContext.Current from within a static class and Method?

I want to store a value on a per-user basis but want to be able to access it in a static manner.

e.g. Will this work?

public static class StaticClass
{

    public static string SomeThing
    {
        get { return HttpContext.Current.Items["SomeItem"].ToString(); }
    }

}

3条回答
Deceive 欺骗
2楼-- · 2019-04-19 13:11

Yes, it's a static method so you can call it from wherever you like. As Anthony says, the "current" context depends on the calling thread, so you need to make sure you're using the correct thread.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-04-19 13:15

Yes thats one way in which it is helpful, of course the thread on which it is called must currently be processing a request to make it useful.

查看更多
冷血范
4楼-- · 2019-04-19 13:23

Why don't you try?

Yes, it's perfectly possible (though is not necessarily a good design), just remember to reference System.Web.dll in your project and check HttpContext.Current for null in case you'll end up running in a non-ASP.NET environment.

查看更多
登录 后发表回答