HttpContext

Represents the context of an HTTP request and response, providing access to request, response, and other useful properties. It's the central object in ASP.NET Core for handling HTTP operations.

Properties

Example Usage

The HttpContext is automatically available in ASP.NET Core controllers, Razor Pages, and middleware.

Accessing Request and Response in a Controller

using Microsoft.AspNetCore.Mvc; public class HomeController : Controller { public IActionResult Index() { // Accessing request information var requestPath = HttpContext.Request.Path; var httpMethod = HttpContext.Request.Method; // Setting response information HttpContext.Response.StatusCode = 200; HttpContext.Response.ContentType = "text/plain"; HttpContext.Response.Headers.Add("X-Custom-Header", "MyValue"); return Content($"Hello from {requestPath} with method {httpMethod}"); } }

Accessing HttpContext in Middleware

using Microsoft.AspNetCore.Http; using System.Threading.Tasks; public class CustomMiddleware { private readonly RequestDelegate _next; public CustomMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { // Accessing request path var path = context.Request.Path; context.Items["OriginalPath"] = path.ToString(); // Storing data in Items // Modifying response context.Response.Headers.Add("X-Powered-By", "CustomMiddleware"); await _next(context); // Call the next middleware in the pipeline } }
To use session state, you must add the AddSession() and UseSession() methods in your Startup.cs or Program.cs file.

Methods