Wednesday, March 27, 2013

ASP.NET MVC Context

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

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. 
  • 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)
You can get HttpContext from HttpContextBase via.

HttpContext context = httpContextBase.ApplicationInstance.Context

Getting HttpContextBase from HttpContext

HttpContextBase abstractContext = new System.Web.HttpContextWrapper(context);
source (link1link2

Getting the HttpContext current inside ASP.NET MVC action (link)
Use System.Web.HttpContext.Current or this.HttpContext.ApplicationInstance.Context


6 comments:

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook