简体   繁体   中英

OnActionExecuted code for all HTTP GET actions in .NET MVC Application

What is the best way to create custom OnActionExecuted code for all HTTP GET actions in a .NET MVC application?

Would you create an ActionFilter, or create a base controller, and in either of these approaches is it possible to fire the action filter only on GET requests?

My initial thinking is a base controller written as follows, but is this the best way, or am I missing something?

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    if (Request.HttpMethod == "GET")
    {
        ...
    }
}

You code is good. I would use:

if (string.Equals(Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))

Also if you would like to create few ActionFilters for 'GET' request only you may create common base ActionFilter class and then derive all concrete action filters from it.

Controller itself is a filter so you can use the controller or you can go for a separate class/filter. You have to analyze which one suits for you. By putting the logic in the controller you may lose unit testing so if testing/SOC are important concerns then I may suggest go for a separate class that encapsulates the logic. Also, you can avoid code duplication if you have two different base controllers in an application (rarely).

The best way to do this turned out to be neither using base controller or custom action filter declared on actions. It's best to globally register the action filter using a controller factory, and requires neither inheriting from a base controller nor adding the action filter on ever controller/action. The action filter is assigned to the Controller ActionInvoker in a custom DefaultControllerFactory derivation declared in global.asax .

This blog post was useful in implementing this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM