15

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(); }
    }

}
Greg B
  • 14,597
  • 18
  • 87
  • 141

3 Answers3

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.

AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
5

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.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
5

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • The class and properties will only be called from within web pages. So I presume I will always get the Current context from correct thread. Is this right or am I missing something? – Greg B Feb 17 '09 at 11:06
  • 2
    It should be okay so long as you're not doing any funky threading (e.g. using the threadpool within your web pages). – Jon Skeet Feb 17 '09 at 11:15
  • Cool, no, I'm not. Cheers Jon – Greg B Feb 17 '09 at 11:18