Click here to Skip to main content
16,020,253 members
Articles / jQuery

Custom Filters in MVC - Authorization , Action, Result, Exception Filters.

Rate me:
Please Sign up or sign in to vote.
4.80/5 (22 votes)
24 Jul 2012CPOL3 min read 192.4K   36   7
CodeProjectFilters in MVC are attributes which you can apply to a controller action or an entire controller. This will allow us to add pre and post behavior to controller action methods. There are 4 types of Filters.

Filters in MVC are attributes which you can apply to a controller action or an entire controller. This will allow us to add pre and post behavior to controller action methods.

There are 4 types of Filters. Which were described in above image.

Objective: Learn about filters and create custom filters for better understanding.

Step 1: Create a simple MVC Web application. Lets see the Output Cache filter first.

I created a View and pertaining Action method. See them below.

View

//OutPutTest.cshtml
@{
    ViewBag.Title = "OutPutTest";
}
lt;h2>OutPutTest</h2>
<h3>@ViewBag.Date</h3>

Action Method

//OutPutTest Action Method
[OutputCache(Duration=10)]
 public ActionResult OutPutTest()
 {
   ViewBag.Date = DateTime.Now.ToString("T");
   return View();
 }

Output : so as per the current implementation, the view should be displaying current time with seconds. so for every refresh, the seconds part will be changed...

But observe the [OutputCache(Duration=10)] attribute applied to action method. This will make the response cached for 10 seconds. Thus the seconds part will not be changed for next 10 seconds.

Step 2: Authorization Filter : This filter will be executed once after user is authenticated

In this step lets create a custom Authorization filter. For this create a class which inherits AuthorizeAttribute or implements IAuthorizationFilter interface. All we are doing here is just passing a message to View.

public class CustAuthFilter : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {            
            filterContext.Controller.ViewBag.AutherizationMessage = "Custom Authorization: Message from OnAuthorization method.";
        }        
    }

Now we have our CustomAuthFilter which will be executed immedealty after user is authenticated. But inorder to make it happen we need to apply this [CustAuthFilter] attribute on top either a custom action or to an entire controller itself.

We have another method OnUnauthorizedRequest event to redirect the unauthorized users to some default pages. Step 3: Action Filter : There are 4 events available in an action filter.

  1. OnActionExecuting - Runs before execution of Action method.
  2. OnActionExecuted - Runs after execution of Action method.
  3. OnResultExecuting - Runs before content is rendered to View.
  4. OnResultExecuted - Runs after content is rendered to view.

So lets create a CustomActionFilter. Create a class inherting ActionFilterAttribute class of implementing IActionFilter and IResultFilter interfaces.

public class CustomActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.Controller.ViewBag.CustomActionMessage1 = "Custom Action Filter: Message from OnActionExecuting method.";
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.Controller.ViewBag.CustomActionMessage2 = "Custom Action Filter: Message from OnActionExecuted method.";
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            filterContext.Controller.ViewBag.CustomActionMessage3 = "Custom Action Filter: Message from OnResultExecuting method.";
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.Controller.ViewBag.CustomActionMessage4 = "Custom Action Filter: Message from OnResultExecuted method.";
        }        
    }

Now all we need to do is to apply [CustomActionFilter] attribute on an Action Method.

Step 4: Exception Filter: This filter is used to capture any execptions if raised by controller or an action method. Create a class which will inherit FilterAttribute class and implement IExceptionFilter interface.

public class CustExceptionFilter : FilterAttribute, IExceptionFilter
    {
        public  void OnException(ExceptionContext filterContext)
        {
            filterContext.Controller.ViewBag.ExceptionMessage = "Custom Exception: Message from OnException method.";
        }        
    }

Now all we need to do to handle any exceptions or erros is to apply [CustExceptionFilter] attribute on an Action Method.

Step 5: Now we have all custom filters created. Lets decorate our index action method with them.

Contoller code:

namespace CustomActionFilterMVC.Controllers
{
    [CustAuthFilter]
    public class HomeController : Controller
    {
       [CustExceptionFilter]
       [CustomActionFilter]
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();            
        }

        public ActionResult About()
        {
            return View();
        }

        [OutputCache(Duration=10)]
        public ActionResult OutPutTest()
        {
            ViewBag.Date = DateTime.Now.ToString("T");
            return View();
        }
    }
}

Step 6: Now update Index view to reflect all the messages from cutom filters.

@{
    ViewBag.Title = "Home Page";
}

<h2>Output Messages :</h2>
<br />
<h3>@ViewBag.AutherizationMessage</h3>
<br />
<h3>@ViewBag.CustomActionMessage1</h3>
<br />
<h3>@ViewBag.CustomActionMessage2</h3>
<br />
<h3>@ViewBag.CustomActionMessage3</h3>
<br />
<h3>@ViewBag.CustomActionMessage4</h3>
<br />
<h3>@ViewBag.ExceptionMessage</h3>

Step 7: Now execute the application and see the out put.

Now compare the output with the view definition and see the differences.

First thing is , we dint have any message from OnResultExecuted event.

Reason: That event will be executed after content is rendered to view, so by that time the view is rendered,  OnResultExecuted event is not and message is not yet assigned to ViewBag.

Second thing, we dint have any message from exception filter. If there is any exception raised by the code, then the Exception Filter codee will come into picture. With this , we have covered different kinds of filters in MVC and how to create custom filters and how to apply them.

Code: Click Here

Is it helpful for you? Kindly let me know your comments / Questions.

This article was originally posted at http://pratapreddypilaka.blogspot.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionMy vote of 1 Pin
Frans Vander Meiren5-Feb-17 9:03
Frans Vander Meiren5-Feb-17 9:03 
The original is much better than the copy.
See Understanding Action Filters (C#) | The ASP.NET Site[^]
QuestionClear Explaination of concept Pin
Sarika Chavhan10-Jan-17 20:08
Sarika Chavhan10-Jan-17 20:08 
QuestionNice Post Need clarification Pin
Member 1191277415-Sep-16 19:55
Member 1191277415-Sep-16 19:55 
GeneralNice Post Pin
Amol Eklare14-Oct-15 4:10
Amol Eklare14-Oct-15 4:10 
GeneralMy vote of 5 Pin
sunilmalhotra23-Jan-15 6:58
sunilmalhotra23-Jan-15 6:58 
QuestionGood Article Easily Understandable Pin
Prabhakar.Vijendar17-Jul-13 18:18
Prabhakar.Vijendar17-Jul-13 18:18 
GeneralMy vote of 3 Pin
sujeshkc5-Jun-13 20:50
sujeshkc5-Jun-13 20:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.