ASP.NET MVC 4 intercept all incoming requests

Viewed 70763

Is there a way for me to catch all incoming requests to my ASP.NET MVC 4 app and run some code before continuing the request onward to the specified controller/action?

I need to run some custom auth code with existing services, and to do this properly, I'll need to be able intercept all incoming requests from all clients to double check some things with the other service.

4 Answers

I'm not sure about MVC4 but I think it is fairly similar to MVC5. If you have created a new web project -> look in Global.asax and you should see the following line FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); in the method Application_Start().

RegisterGlobalFilters is a method in the file FilterConfig.cs located in the folder App_Start.

As @YngveB-Nilsen said ActionFilterAttribute is the way to go in my opinion. Add a new class that derives from System.Web.Mvc.ActionFilterAttribute. This is important because System.Web.Http.Filters.ActionFilterAttribute will fail with the following exception for example.

The given filter instance must implement one or more of the following filter interfaces: System.Web.Mvc.IAuthorizationFilter, System.Web.Mvc.IActionFilter, System.Web.Mvc.IResultFilter, System.Web.Mvc.IExceptionFilter, System.Web.Mvc.Filters.IAuthenticationFilter.

Example that writes the request to the debug window:

public class DebugActionFilter : System.Web.Mvc.ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext actionContext)
  {
    Debug.WriteLine(actionContext.RequestContext.HttpContext.Request);
  }
}

In FilterConfig -> RegisterGlobalFilters -> add the following line: filters.Add(new DebugActionFilter());.

You can now catch all incoming requests and modify them.

Related