jobmo
jobmo

Reputation: 866

What´s the difference between a custom action filter and a custom action selector in ASP.NET MVC?

I would like to know the differences between a custom action filter and a custom action selector in ASP.NET MVC.

Say we want to restrict who can have access to an action method on a controller based on some rules. I could either create an action filter extending the ActionFilterAttribute class or extending the ActionMethodSelectionAttribute class, so that I could have something like:

[MyRestriction]
public ActionResult AnyAction(){}

Could anyone explain the differences between them so that I can make the right decision?

Upvotes: 1

Views: 833

Answers (1)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93464

If you look at the documentation for ActionMethodSelectionAttribute, you will see at the very bottom of the page that there are a number of other classes that derive from this attribute.

These include:

  • Microsoft.Web.Mvc.AjaxOnlyAttribute
  • System.Web.Mvc.AcceptVerbsAttribute
  • System.Web.Mvc.HttpDeleteAttribute
  • System.Web.Mvc.HttpGetAttribute
  • System.Web.Mvc.HttpHeadAttribute
  • System.Web.Mvc.HttpOptionsAttribute
  • System.Web.Mvc.HttpPatchAttribute
  • System.Web.Mvc.HttpPostAttribute
  • System.Web.Mvc.HttpPutAttribute
  • System.Web.Mvc.NonActionAttribute

In other words, these are the attributes which control which Action Method is selected during routing when there are several different choices to choose from (ie there are 2 different Index methods, one decorated with [HttpGet] and one with [HttpPost]).

ActionFilterAttribute, on the other hand, is called only when an action is actually executing.

Think about it this way, The selection can run even if the action doesn't execute, the ActionFilter only runs if it does. The selection filter is only used to determine whether the action is a match condition, the action filter is used to do some action before, after, etc.. the action or response is executed.

Upvotes: 4

Related Questions