Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Web .Net: Intercept all calls before reaching controller?

Tags:

.net

asp.net

I have a .Net MVC web application (Not WebAPI), and I want to intercept all calls to the web app before they reach the controller, check for a value in the request headers, and do something if the value isn't present (such as presenting a 404). What's the ideal way to do this? Keep in mind this is not a Web API application, just a simple web application.

like image 623
Henley Avatar asked Apr 17 '13 19:04

Henley


People also ask

What is redirect to route in MVC?

RedirectToRoute(String, RouteValueDictionary)Redirects to the specified route using the route name and route dictionary.

How can we detect that a MVC controller is called by post or get?

You can check the Request. HttpMethod property. Save this answer.


2 Answers

Depending on what specifically you want to do, you could use a default controller which all other controllers extend. That way you can override OnActionExecuting or Initialize and do your check there.

public class ApplicationController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //do your stuff here
    }
}

public class YourController : ApplicationController
{

}
like image 157
Mansfield Avatar answered Nov 02 '22 23:11

Mansfield


You're looking for global action filters.

Create a class that inherits ActionFilterAttribute, override OnActionExecuting() to perform your processing, and add an instances to global filter collection in Global.asax.cs (inside RegisterGlobalFilters())

like image 38
SLaks Avatar answered Nov 02 '22 23:11

SLaks