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
-
Request
HttpRequest
Gets the HttpRequest object associated with the current HTTP request.
This object provides information about the incoming request, such as headers, body, query parameters, and the request path.
-
Response
HttpResponse
Gets the HttpResponse object associated with the current HTTP response.
This object is used to send data back to the client, including setting status codes, headers, and writing to the response body.
-
Connection
ConnectionInfo
Gets information about the network connection used for the request.
This includes details like the client's IP address, port, and local server endpoint.
-
Session
ISession
Gets or sets the session state for the current request. Requires session state middleware to be enabled.
-
Items
IDictionary<object, object>
Gets a collection of key-value pairs that can be used to share data between middleware components and the application.
This is a convenient place to store request-specific data that doesn't fit neatly into other 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
}
}
AddSession() and UseSession() methods in your Startup.cs or Program.cs file.
Methods
-
Abort()
void Abort()
Aborts the connection.
-
Features
IFeatureCollection Features { get; }
Gets the collection of features available on this context.
This allows access to lower-level request and response features.