Sunday, January 7, 2018

Filters in MVC

MVC Filters are used to execute custom logic before or after executing action method.
MVC Filter types:
Authorization filters
Action filters
Result filters
Exception filters
Filters can be applied globally in FilterConfig class, at controller level or action method level.
Custom filter class can be created by implementing FilterAttribute class and corresponding interface.


Authorization filters : Perform authentication and authorizes before executing action method.
Build-in filter are [Authorize],[RequireHttps] and interface is IAuthorizationFilter. IAuthorization contains one method OnAuthorization

Action filters : Perform some operation before and after the action method. Interface name is IActionFilter. Example : View Data Modification, OutputCache is an ex of Action Filter.

IAction Filter contains two methods
OnActionExecuting - Runs before execution of Action method.
OnActionExecuted - Runs after execution of Action method.

Result Filter : Perform some operation before or after the execution of View result. Built-in filter is [OutputCache]
and interface is IResultFilter.

IResultFilter contains two methods

OnResultExecuting - Runs before content is rendered to View.
OnResultExecuted - Runs after content is rendered to view.

Excepton Filter : Perform some operation if there is an unhandled exception
thrown during the execution of the ASP .net MVC pipleine. Built-i filter is [HandleError] and interface is IExceptionFilter.


IExceptionFilter contains one method

OnException

An exception filter execute when there is an unhandled exception occurs in application.
HandleErrorAtribute([HandleError]) class is a built-is exception filter class.It renders Error.cshtml
included in Shared.

Please make sure that CustomError mode is on in System.web section of web.config, in order for HandleErrorAttribute work properly.

<customErrors mode="On" />

Some built-in filter

AuthorizeAttribute. Restricts access by authentication and optionally authorization.
HandleErrorAttribute. Specifies how to handle an exception that is thrown by an action method.
OutputCacheAttribute. Provides output caching.
RequireHttpsAttribute. Forces unsecured HTTP requests to be resent over HTTPS.

Register Filters
Filters can be applied at three level.

Global Level : In Application_Start event by using
default FilterConfig.RegisterGlobalFilters() method.

Global filters will be applied to all the controller and action methods of an application.

The [HandleError] filter is applied globaly in MVC Application by default in every MVC application created using Visual Studio as shown below.
of Global.asax by using default

// MvcApplication class contains in Global.asax.cs file 
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    }
}

// FilterConfig.cs located in App_Start folder 
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}

2. Controller level

Filters can also be applied to the controller class. So, filters will be applicable to all the action method of Controller class if it is applied to a controller class.

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

}

3. Action method level:

You can apply filters to an individual action method also.

public class HomeController : Controller
{
    [HandleError]
    public ActionResult Index()
    {
        return View();
    }

}

The same way, you can apply multiple built-in or custom filters globally or at controller or action method level for different purpose such as [Authorize],[RequireHttps], [ChildActionOnly],[OutputCache],[HandleError].

Filter Order:
As mentioned above, MVC includes different types of filters and multiple filters can be applied to a single controller class or action method. So, filters run in the following order.

Authorization filters
Action filters
Response filters
Exception filters

Create Custom Filter:
You can create custom filter attributes by implementing an appropriate filter interface for which you want to create a custom filter and also derive a FilterAttribute class so that you can use that class as an attribute.

For example, implement IExceptionFilter and FilterAttribute class to create custom exception filter. In the same way implement an IAuthorizatinFilter interface and FilterAttribute class to create a custom authorization filter.

class MyErrorHandler : FilterAttribute, IExceptionFilter
{
    public override void IExceptionFilter.OnException(ExceptionContext filterContext)
    {
        Log(filterContext.Exception);

        base.OnException(filterContext);
    }

    private void Log(Exception exception)
    {
        //log exception here..

    }
}

Alternatively, you can also derive a built-in filter class and override an appropriate method to extend the functionality of built-in filters.

class MyErrorHandler : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        Log(filterContext.Exception);

        base.OnException(filterContext);
    }

    private void Log(Exception exception)
    {
        //log exception here..

    }
}

Canceling Filter Execution

You can cancel filter execution in the OnActionExecuting and OnResultExecuting methods by setting the Result property to a non-null value.

No comments:

Followers

Link