Explain the role of HttpContext class in ASP.NET Core


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.

The HttpContext object constructed by the ASP.NET Core web server acts as a container for a single request. It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any.

ASP.NET Core applications access the HTTPContext through the IHttpContextAccessor interface. The HttpContextAccessor class implements it. You can use this class when you need to access HttpContext inside a service.

Different Ways to Access HttpContext

Here are different ways to access HttpContext from various types of applications.

From a Controller:

public class HomeController : Controller{
   public IActionResult About(){
      var pathBase = HttpContext.Request.PathBase;

      ...

      return View();
   }
}

From Razor Pages:

public class AboutModel : PageModel{
   public string Message { get; set; }

   public void OnGet(){
      Message = HttpContext.Request.PathBase;
   }
}

From a Razor View:

@{
   var username = Context.User.Identity.Name;

   ...
}
From middleware
public class MyCustomMiddleware{
   public Task InvokeAsync(HttpContext context){
      ...
   }
}

Useful properties and methods on HttpContext

Here are some of the useful properties and methods on the HttpContext object.

Properties:

  • Connection: Gets the information about the underlying network connection for this request.
  • Request: Gets the HttpRequest object for this request
  • Response: Gets the HttpResponse object for this request
  • Session: Gets or sets the object used to manage the user session data for this request

Methods

  • Abort(): Aborts the connection underlying the request.

In ASP.NET Core, the Kestrel web server receives the HTTP request and constructs a C# representation of the request, the HttpContext object. However, Kestrel doesn't generate the response itself but forwards the HttpContext object to the middleware pipeline in the ASP.NET Core application. Middleware is a series of components that process the incoming request and perform various operations such as authentication, caching, logging, etc.

Updated on: 22-Jun-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements