ASP.NET MVC Request filters
Doesn't ASP.NET MVC support some kind of开发者_如何学JAVA RequestFilters - the filters which are executed once per request before controllers and actions instantiation?
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());
}
There are action filters in ASP.NET MVC which allow you to run some custom code at different stages of the execution of the request.
- Before an action is executed
- After an action is executed
- Before the result is rendered
- After the result is rendered
Depending of the code you are willing to execute and the kind of functions you want to perform there might be other ways to plug into the framework.
精彩评论