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(); }
}
}
The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.
HttpContext isn't thread-safe. Reading or writing properties of the HttpContext outside of processing a request can result in a NullReferenceException.
This property is a static property of the HttpContext class. The property stores the HttpContext instance that applies to the current request. The properties of this instance are the non-static properties of the HttpContext class. You can also use the Page.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With