3

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")
    {
        ...
    }
}
Zaid Masud
  • 13,225
  • 9
  • 67
  • 88

3 Answers3

0

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.

petro.sidlovskyy
  • 5,075
  • 1
  • 25
  • 29
0

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).

VJAI
  • 32,167
  • 23
  • 102
  • 164
0

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.

Community
  • 1
  • 1
Zaid Masud
  • 13,225
  • 9
  • 67
  • 88