Please enable Javascript to correctly display the contents on Dot Net Tricks!

Understanding ASP.NET MVC Filters and Attributes

 Print 
  Author : Shailendra Chauhan
Posted On : 28 Jan 2014
Total Views : 248,455   
Updated On : 14 Feb 2017
 

ASP.NET MVC provides a simple way to inject your piece of code or logic either before or after an action is executed. This is achieved by decorating the controllers or actions with ASP.NET MVC attributes or custom attributes. An attribute or custom attribute implements the ASP.NET MVC filters(filter interface) and can contain your piece of code or logic. You can make your own custom filters or attributes either by implementing ASP.NET MVC filter interface or by inheriting and overriding methods of ASP.NET MVC filter attribute class if available.

When to use Filters?

Typically, Filters are used to perform the following common functionalities in your ASP.NET MVC application.

  1. Custom Authentication

  2. Custom Authorization(User based or Role based)

  3. Error handling or logging

  4. User Activity Logging

  5. Data Caching

  6. Data Compression

Types of Filters

The ASP.NET MVC framework provides five types of filters.

  1. Authentication filters (New in ASP.NET MVC5)

  2. Authorization filters

  3. Action filters

  4. Result filters

  5. Exception filters

Authentication Filters

This filter is introduced with ASP.NET MVC5. The IAuthenticationFilter interface is used to create CustomAuthentication filter. The definition of this interface is given below-

public interface IAuthenticationFilter
{
 void OnAuthentication(AuthenticationContext filterContext);

 void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
}

You can create your CustomAuthentication filter attribute by implementing IAuthenticationFilter as shown below-

public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
 public void OnAuthentication(AuthenticationContext filterContext)
 { 
 //Logic for authenticating a user
 }
 //Runs after the OnAuthentication method
 public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
 { 
 //TODO: Additional tasks on the request
 }
}

Authorization Filters

The ASP.NET MVC Authorize filter attribute implements the IAuthorizationFilter interface. The definition of this interface is given below-

public interface IAuthorizationFilter
{
 void OnAuthorization(AuthorizationContext filterContext);
}

The AuthorizeAttribute class provides the following methods to override in the CustomAuthorize attribute class.

public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
 protected virtual bool AuthorizeCore(HttpContextBase httpContext);
 protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
 public virtual void OnAuthorization(AuthorizationContext filterContext);
 protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
}

In this way you can make your CustomAuthorize filter attribute either by implementing IAuthorizationFilter interface or by inheriting and overriding above methods of AuthorizeAttribute class.

Action Filters

Action filters are executed before or after an action is executed. The IActionFilter interface is used to create an Action Filter which provides two methods OnActionExecuting and OnActionExecuted which will be executed before or after an action is executed respectively.

public interface IActionFilter
{
 void OnActionExecuting(ActionExecutingContext filterContext);
 void OnActionExecuted(ActionExecutedContext filterContext);
}

Result Filters

Result filters are executed before or after generating the result for an action. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult which derives from the ActionResult class. Result filters are called after the Action filters. The IResultFilter interface is used to create an Result Filter which provides two methods OnResultExecuting and OnResultExecuted which will be executed before or after generating the result for an action respectively.

public interface IResultFilter
{
 void OnResultExecuted(ResultExecutedContext filterContext);
 void OnResultExecuting(ResultExecutingContext filterContext);
}

Exception Filters

Exception filters are executed when exception occurs during the actions execution or filters execution. The IExceptionFilter interface is used to create an Exception Filter which provides OnException method which will be executed when exception occurs during the actions execution or filters execution.

public interface IExceptionFilter
{
 void OnException(ExceptionContext filterContext);
}

ASP.NET MVC HandleErrorAttribute filter is an Exception filter which implements IExceptionFilter. When HandleErrorAttribute filter receives the exception it returns an Error view located in the Views/Shared folder of your ASP.NET MVC application.

Order of Filter Execution

All ASP.NET MVC filter are executed in an order. The correct order of execution is given below:

  1. Authentication filters

  2. Authorization filters

  3. Action filters

  4. Result filters

Configuring Filters

You can configure your own custom filter into your application at following three levels:

  1. Global level

    By registering your filter into Application_Start event of Global.asax.cs file with the help of FilterConfig class.

    protected void Application_Start()
    {
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    }
    
  2. Controller level

    By putting your filter on the top of the controller name as shown below-

    [Authorize(Roles="Admin")]
    public class AdminController : Controller
    {
     //
    }
    
  3. Action level

    By putting your filter on the top of the action name as shown below-

    public class UserController : Controller
    {
     [Authorize(Users="User1,User2")]
     public ActionResult LinkLogin(string provider)
     {
     // TODO:
     return View();
     }
    }
    
What do you think?

I hope you will enjoy the ASP.NET MVC filter while extending ASP.NET MVC framework. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.



Free Interview Books
 
COMMENTS
Piyush Choudhary Reply 67 days 22 hours 49 mins ago

Sir, just have small query if i implemented a Action Filter and registered it globally, then will it fire for each contoller action??

Vaibhav Agarwal Reply 199 days 19 hours 9 mins ago

Can I see some example or project where I can see implementation of all overrides of all these attributes?

Balaji Viswanathan Reply 205 days 16 hours 43 mins ago

It is excellent. Thank you. I have below questions,could you plese explain me. 1) Is HttpPost,HttpGet are filters ? 2) All attributes in mvc are Filters ?

24 SEP
Angular2 and Angular4 (Classroom)
08:30 AM-11:30 AM IST
23 SEP
MEAN Stack (Classroom)
8:30 Am To 11:30 Am
23 SEP
Microsoft Azure Infrastructure Solutions (Online)
08:00 PM-11:00 PM IST / 9:30 AM-12:30 PM CST
20 SEP
MEAN Stack (Online)
07:00 AM-09:00 AM IST
20 SEP
ASP.NET MVC with Angular4 (Online)
9:00PM- 11:00PM IST(+5:30GMT)
16 SEP
Angular2 and Angular4 (Online)
08:00 AM-10:00 AM IST(+5.30 GMT)
7 SEP
ASP.NET MVC with Angular4 (Online)
09:00 PM to 11:00 PM IST (+5:30 GMT)
22 AUG
ASP.NET Core with Angular4 (Online)
07:00 AM - 9:00 AM IST(+5:30 GMT)
19 AUG
MEAN Stack 2 (Online)
5:30 Pm - 7:00 PM IST (+5:30 GMT)
19 AUG
ASP.NET MVC with Angular4 (Online)
10:30 Am to 12:30 PM IST (+ 5:30 GMT)
19 AUG
NodeJS with Angular4 (Classroom)
04:00 PM to 07:00 PM IST (+5:30 GMT)
12 AUG
ASP.NET MVC with Angular4 (Classroom)
11:30 AM - 1:30 PM IST (+5:30GMT)
15 JUL
ASP.NET MVC with Angular4 (Online)
03:30 PM - 05:30 PM IST(+5.30 GMT)
LIKE US ON FACEBOOK
 
+