Advertisement
Intermediate ASP.NET Core, Filters

How can filters access route values, query string parameters, or the raw HttpContext during execution?

Short answer

Every filter context type (ActionExecutingContext, ResourceExecutingContext, etc.) exposes HttpContext directly, giving access to Request.Query, Request.RouteValues, Request.Headers, and all standard HttpContext members -- letting a filter make decisions based on the full…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Every filter context type (ActionExecutingContext, ResourceExecutingContext, etc.) exposes HttpContext directly, giving access to Request.Query, Request.RouteValues, Request.Headers, and all standard HttpContext members -- letting a filter make decisions based on the full request context, not just the strongly-typed action arguments that model binding produces.
public class TenantValidationFilter : IActionFilter {
    public void OnActionExecuting(ActionExecutingContext context) {
        var tenantId = context.HttpContext.Request.Headers["X-Tenant-Id"].ToString();
        if (string.IsNullOrEmpty(tenantId)) {
            context.Result = new BadRequestObjectResult("Missing tenant header");
        }
    }
    public void OnActionExecuted(ActionExecutedContext context) { }
}
Real-world example
A multi-tenant SaaS API uses a filter that reads a custom X-Tenant-Id header directly from HttpContext.Request.Headers to validate every request belongs to a valid tenant before the action method even runs.
Likely follow-ups
  • How does this differ from accessing the same data via constructor-injected IHttpContextAccessor in a service?
  • What's the risk of filters becoming tightly coupled to HttpContext internals?
Related topics