ASP.NET Core Interview Question #83
What is HttpContext in ASP.NET Core?
Middleware & Request Pipeline Mid-Level Intermediate
Quick Interview Answer
HttpContext represents the current HTTP request and response. It provides access to Request, Response, User, Connection, Session when configured, Items, RequestServices, and other request-specific information.
Detailed Explanation
HttpContext represents the current HTTP request and response. It provides access to Request, Response, User, Connection, Session when configured, Items, RequestServices, and other request-specific information.
Middleware, controllers, endpoint handlers, and other web-layer components use HttpContext to interact with the active request.
Business logic should generally avoid depending directly on HttpContext because doing so couples domain or application services to the web framework. Pass only the information those services actually require.
Code Example
app.Use(async (context, next) =>
{
var path = context.Request.Path;
var userName = context.User.Identity?.Name;
context.Response.Headers["X-App-Name"] = "MyApp";
await next();
});