HttpContext encapsulates all HTTP-specific information about an individual HTTP request. HttpContext resides in System.Web namespace which contains classes and interfaces for browser-server communication. HttpContext also implements IServiceProvider interface. You can access current context using HttpContext.Current property.
Web API doesn't directly include HttpContext because REST API supposed to be completly stateless (other than cookies and other client-side state) but you can access it like in this example.
Web API doesn't directly include HttpContext because REST API supposed to be completly stateless (other than cookies and other client-side state) but you can access it like in this example.
Difference between System.Web.HttpContext.Current and Controller.Context (HttpContext vs. HttpContextBase) (link)
- Both are usually identical
- The type of HttpContext.Current is also HttpContext
- The type of Controller.Context is HttpContextBase
- Both implements IServiceProvider interface
- When working on additional threads, System.Web.HttpContext.Current is threadstatic
- Threadstatic means value is tied to the thread. In any additional thread, you cannot access HttpContext.Current
- The context provided by the controller is mockable (for unit testing)
- You can access System.Web.HttpContext.Current from any code inside the same application domain. But be careful to separate the layers
- If you have a layered architecture its fine to access context from within web project but it is not a good practice to access it from a class library project (the project in which you keep your business logic).
- In ASP.NET HttpApplication has a reference to HttpContext through its Context property. in ASP.NET MVC Controller class has Context property of type HttpContextBase.
- HttpApplication is the class from which Global.asax is created. (odetocode : Global.asax and HttpApplication)
- The idea behind introducing HttpContextBase abstract away dependencies to allow unit testing because HttpContextBase is an abstract class. (link)
- Why HttpContext not derive from HttpContextBase (another link)
Getting the HttpContext current inside ASP.NET MVC action (link)
Use System.Web.HttpContext.Current or this.HttpContext.ApplicationInstance.Context