ASP.NET MVC Filter with example

ASP.NET MVC Filter is a custom class (attribute) where you can write custom logic to execute before or after an action method executes.

In simple words:

Filters are attribute which is used to perform some logic before and after an action method is called.

                  

When to use filters? (Example)

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

 

Type 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

 

NOTE: All ASP.NET MVC filters are executed in the above order.

 

Below is the list of all the filters including the built-in filters and interfaces that must be implemented to create custom filters.

 

 


Authentication Filter

The authentication filter is used to confirm the validity of a user for the requested page. Before any other filter is executed, it is the first to be executed. The IAuthenticationFilter interface is implemented by two methods.

 

1. OnAuthentication- which will call when user verification is completed.

2. OnAuthenticationChallenge - which will call after authorization or authentication fail, after an action method is called, and before your view is rendered.

public interface IAuthenticationFilter {

    void OnAuthentication(AuthenticationContext filterContext);

    void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);

}

 

Authorization Filter

When authorization is needed, this Filter is called. It is called just after the Authentication filter and before the Action filter. This Filter authorizes the user with their role. An authorization filter is implemented by using the "Authorize" attribute.

authorizationFilter implements the IauthorizationFilter interface, which only defines one method, "OnAuthorization," called at authorization time.

 

public interface IAuthorizationFilter {

    void OnAuthorization(AuthorizationContext filterContext);

 

ActionFilter

Action filters can be applied to either a controller section or the entire controller to modify how an action is executed.

 

public interface IActionFilter {

    void OnActionExecuted(ActionExecutedContext filterContext);

    void OnActionExecuting(ActionExecutingContext filterContext);

}

Result Filter

Like Action Filter, it modifies your view before rendering. It can also perform extra custom logic following rendering. Therefore, it is mainly used for rendering results that you want to display on the view.

This interface implements IresultFilter, which has two methods, OnResultExecuted and OnResultExecuting, which are called just after your result is created.

 

public interface IResultFilter {

    void OnResultExecuted(ResultExecutedContext filterContext);

    void OnResultExecuting(ResultExecutingContext filterContext);

}

 

Exception Filter

If you need to log exception messages in response to an exception. The "HandleError" attribute provides an inbuilt exception filter. This interface implements IExceptionFilter,

Only one method defined as OnException, and is called whenever an exception occurs.

 

public interface IExceptionFilter {

    void OnException(ExceptionContext filterContext);

}

Types of Action Filter

Action filter in ASP.NET MVC has:

1.      OutputCache

2.      HandleError

3.      Authorize

 

OutputCache Action Filter:-

One of the best ways to improve the performance of an ASP.NET MVC Application is by caching. With the help of caching, we can reduce hosting and the database Server round trips. We can apply Outputcache Action Filter either on Action Method or on the controller. OutputCache attribute has several properties like CacheProfile, Duration, Location, VaryByParam, VaryByHeader, NoStore etc.

Example:

The return value is specified to be cached for 10 seconds.

 

using System;

using System.Web.Mvc;

using System.Collections.Generic;

 

namespace ActionFilter {

    public class HomeController: Controller {

        [HttpGet]

        [OutputCache(Duration = 10)]

        public string Index() {

            return DateTime.Now.ToString("T");

        }

    }

}

 

 

HandleError Action Filter:-

HandleError Attribute has a couple of properties which are useful in handling an exception and help in modifying the default behaviour of HandleError Attribute.

To use HandleError in MVC application, we are required 3 things in our application:-

1. We have to add Custom Error in web.config file.

<system.web> 

    <customErrors mode="On"></customErrors> 

</system.web> 

2. Add shared folder in Views and then add an Error View (error.cshtml), which will be shown when an exception is thrown.

error.cshtml

@{ 

    Layout = "~/Views/Shared/_Layout.cshtml"; 

 

<h3>An error occurred while processing your request.</h3>

 3. Add HandleError Attribute on About Action method of HomeController.

[HandleError] 

public ActionResult About() 

            //Throws an exception for demonstration 

            throw new Exception("Some unknown error encountered!"); 

            return View(); 

 

ASP.NET MVC Filter with example ASP.NET MVC Filter with example Reviewed by NEERAJ SRIVASTAVA on 6:40:00 PM Rating: 5

No comments:

Powered by Blogger.