Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Current accessed in static classes

Tags:

c#

static

asp.net

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

}
like image 886
Greg B Avatar asked Feb 17 '09 10:02

Greg B


People also ask

How does HttpContext current work?

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.

Is HttpContext current items thread safe?

HttpContext isn't thread-safe. Reading or writing properties of the HttpContext outside of processing a request can result in a NullReferenceException.

What is HttpContext current in C#?

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.


2 Answers

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.

like image 71
AnthonyWJones Avatar answered Oct 08 '22 18:10

AnthonyWJones


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.

like image 29
Anton Gogolev Avatar answered Oct 08 '22 18:10

Anton Gogolev