Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • ASP.NET MVC : Filters and Attributes

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 263
    Comment on it

    ASP.NET MVC provides a simple way to inject the pre-processing and post-processing logic for an action. This is achieved by adorning the controllers/ actions with ASP.NET MVC attributes.

    For example in the below piece of code we have adorned the method with Authorize attribute:

    public ActionResult Index()
        return View();

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

    1) Authentication filters

    Authentication filters are applied prior to any Authorization filters.Prior to ASP.NET MVC 5 we were using the Authorization attribute to enforce role-based security within the ASP.NET MVC applications. Authentication filters process credentials in the request and provide a corresponding principal.

    2) Authorization filters

    Authorization filters are the filters that execute before invocation of other kinds of filters and action method. These filters are used to enforce authorization policy, once the filter has been applied only approved users will be able to access the action method.

    3) Action filters

    This filter will be called before the action starts executing and after the action has executed. We can put our custom pre-processing and post-processing logic in this filter.For using this filter we need to first create a custom filter attribute class and then implement the IActionFilter filter interface. This interface provides us two methods OnActionExecuting and OnActionExecuted which will be called as there name suggests before and after the action gets executed.

    4) Result filters

    We use this filter in scenarios where we want to do some modification in the action's result.To implement the result filters we need to create a custom filter attribute class and implement the IResultFilter interface. This interface provides two methods OnResultExecuting and OnResultExecuted which will be called before and after the action result respectively.

    5) Exception filters

    This filter is invoked the moment a controller or action of the controller throws an exception. This filter is useful when we need to implement error logging in the application.The implementation of this filter requires that we create a custom filter attribute class which implements the interface IExceptionFilter.This interface gives us a method by the name OnException where we can place a call to the the exception logging module.

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: