Doesn't ASP.NET MVC support some kind of RequestFilters - the filters which are executed once per request before controllers and actions instantiation?
as you can see from the below diagram, as soon as the controller starts execution through Action Invoker, Authentication and authorization filters are the very first filters to be triggered, followed by model binding which maps request and route data to action parameters.
The ASP.NET MVC framework supports four different types of filters − Authorization Filters − Implements the IAuthorizationFilter attribute. Action Filters − Implements the IActionFilter attribute. Result Filters − Implements the IResultFilter attribute. Exception Filters − Implements the IExceptionFilter attribute.
You could create your own Routing Handler which might be early enough in the pipeline to achieve your goal.
public class MyRoutingHandler : IRouteHandler
{
protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new InterceptingMvcHandler(requestContext);
}
IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
{
return GetHttpHandler(requestContext);
}
}
and the corresponding mvc handler:
public class InterceptingMvcHandler : MvcHandler
{
public InterceptingMvcHandler(RequestContext requestContext) : base(requestContext)
{
}
protected override IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state)
{
httpContext.Response.Write("<h2>BeginProcessRequest</h2>");
return base.BeginProcessRequest(httpContext, callback, state);
}
protected override void EndProcessRequest(IAsyncResult asyncResult)
{
var context = RequestContext.HttpContext;
base.EndProcessRequest(asyncResult);
if (context != null)
{
context.Response.Write("<h2>EndProcessRequest</h2>");
}
}
}
You can then register the mvc handler in your route registrations.
here is an example for you;
public class CompressFilter : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
HttpRequestBase request = filterContext.HttpContext.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding)) return;
acceptEncoding = acceptEncoding.ToUpperInvariant();
HttpResponseBase response = filterContext.HttpContext.Response;
if (acceptEncoding.Contains("GZIP")) {
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
} else if (acceptEncoding.Contains("DEFLATE")) {
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}
ones you created it, you can use it per action, per controller or even for global project basis;
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new CompressFilter());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With