What is the difference between attributes and filters in MVC

S.A. picture S.A. · Aug 29, 2013 · Viewed 39.9k times · Source

Now can I please get a comparison not just a definition.

Example:

SomeClassAttribute (or ISomeClassAttribute)

VS

SomeClassFilter (or ISomeClassFilter)

I have a feeling that they can be used the same way but generally speaking "an attribute is applied" and a "filter is the functionality they produce." So I could "add an attribute to a method (or class or whatever) to apply a filter.

Answer

asymptoticFault picture asymptoticFault · Aug 29, 2013

"So I could "add an attribute to a method (or class or whatever) to apply a filter."

You've got it in that sentence right there. Filters and Attributes are not exactly comparable concepts, they serve two different functions.

I believe Filtering in MVC is very well covered in this MSDN article.

Attributes (at least those that apply to the filters) mark what the filter is applied to, i.e. an action method or a controller. An example would be the Authorize attribute. This attribute corresponds to an AuthorizationFilter that implements the IAuthorizationFilter interface. Applying the Authorize attribute to an action method tells MVC to authorize a request targeting that action method, applying it to a controller tells MVC to authorize any request targeting an action method of the controller, or authorization can also be applied globally for all requests. Now I said before, at least those that apply to the filters, because Attributes are a concept and syntax of .NET and not just MVC. There are attributes for so many other things and are generally to provide additional information about the property, method, class, they are applied to.