Thursday, August 24, 2017

To Get HTTP-specific information about the current request.

HttpContext

ASP.NET core infrastructure is built around HttpApplication class
which has a reference to System.Web.HttpContext (System.Web) class’s instance in its Context property.

The problem with this is that it has no base class and isn't virtual,
and hence is unusable for testing (cannot mock it).
It's recommended to not pass it around as function arguments, instead pass around variables of type HttpContextBase.

HttpContextBase

This is the (new to c# 3.5) replacement to HttpContext.
Since it is abstract, it is now mockable.
The idea is that your functions that expect to be passed a context should expect to receive one of these.
It is concretely implemented by HttpContextWrapper.

ASP.NET MVC on the other hand uses System.Web.HttpContextBase.Controller class has Context property of type System.Web.HttpContextBase.
Idea behind introducing the new HttpContextBase instead of HttpContext is to allow unit-testing due to HttpContextBase is an abstract class.

HttpContextWrapper

Encapsulates the HTTP intrinsic object that contains HTTP-specific information about an individual HTTP request.

Also new in C# 3.5 - this is the concrete implementation of HttpContextBase.
To create one of these in a normal webpage, use new HttpContextWrapper(HttpContext.Current).

The idea is that to make your code unit-testable,
you declare all your variables and function parameters to be of type HttpContextBase,
and use an IOC framework .
In normal code, castle is to inject the equivalent of 'new HttpContextWrapper(HttpContext.Current)',
whereas in test code you're to be given a mock of HttpContextBase.


But sometimes we may need to convert HttpContext into HttpContextBase and vice versa.
E.g. when we have common logic which is being used from HttpApplication and from MVC controllers.

Getting HttpContext from HttpContextBase’s instance is easy:
HttpContext httpContext = httpContextBase.ApplicationInstance.Context;

To get HttpContextBase from HttpContext we have to wrap it in HttpContextWrapper:
HttpContextBase abstractContext = new System.Web.HttpContextWrapper(context);

No comments:

Change default Port on Next.js app

 If any other app or process is running on port 3000 , you will get this error in your terminal Port 3000 is already in use. error Command f...