Filters in MVC

Filters in MVC codeisall.com
Filters in MVC codeisall.com

Introduction

In the previous article, you learned about what is Areas, the advantages of Areas, and how to use them in an MVC application.

In this article, you will learn about what is Filters, the types of filters, the advantages of filters, and how to use them in an MVC application.

This article will be helpful to beginners and students who are learning.

What are Filters?

A filter is a piece of code or a method that you want to execute before or after any request routed to the appropriate controller and action method.

MVC Filter is a custom class where you can write custom logic to execute before or after an action executes. 

Filters can be declared on the method or a controller by filter attribute or they can be applied programmatically by implementing a corresponding interface.

That type of implementation is called cross-cutting concerns. So, in simple words, this adds extra logic to be implemented into the request being processed. Some of the examples of cross-cutting concerns are Authorization & Output Caching.

Types of Filters in ASP.NET MVC:

There are five types of filters in MVC

Authentication Filters :

those are used to confirm that you are a valid or invalid user while you request any action, if you are a valid user then only you can access that method.

Authentication Filters implement IAuthenticationFilter interface.

Authorization Filters :

Authorization filters are used to check the user access while they request any action.  Authorize attribute and Require Https attribute are examples of Authorization Filters. The Authorize filter is an example of an Authorization filter.

Authorization filters implement IAuthorizationFilterinterface.

Action Filters:

Those are used to run the piece of code before or after calling any action, and after the action has been executed. An action filter is an attribute that you can apply to the action or on the entire controller.

It implements the IActionFilter interface, which contains two methods OnActionExecuting and OnActionExecuted. These filters contain the logic that can be executed after or before calling the action. Action filters can be used to modify the view data the returns by the action.

Result Filters:

Result filters contain a code that can be executed before and after a view result is executed. If you want to modify a view result right before the view is rendered to the browser.

Result Filters implement the IResultFilter interface which is like the IActionFilter has OnResultExecuting and OnResultExecuted. An example of Result Filters is OutputCacheAttribute class. 

ExceptionFilters :

Exception filters can be used as an exception filters to handle errors raised by your controller action results.

Exception Filters implement the IExceptionFilter interface and they execute if there are any unhandled exceptions thrown during the execution. An example of Exception Filters is HandleErrorAttribute class.

Example :

Authentication Filters :

Create a class and replace the below code to create the custom authentication. ResloveActionFilterAttribute and IAuthenticationFilter form the “using System.Web.MVC.Filters;” namespace.

public class AuthAttribute : 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    
    }
}

Now to use this custom authentication, on action write the class name as an attribute as shown below code. Add the reference of the class that you have created.

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

Authorization Filters :

This filter is used to ensure that the requested action can be invoked by the approved users only. A common example of an authorization filter is role-based access to any action, suppose there are two roles admin and user, where the user can only view data and the admin can manipulate the data.

public class AuthAttribute : AuthorizeAttribute
{
    private bool localAllowed;
    public AuthAttribute(bool allowedParam)
    {
        localAllowed = allowedParam;
    }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Request.IsLocal)
        {
            return localAllowed;
        }
        else
        {
            return true;
        }
    }
}

Use the created filter in the Home.cs controller.

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

Action Filters:

There are 3 types of Action filters:

  • Output Cache: This action filter caches the output of a controller action.
  • Handle Error: This action filter handles errors raised when a controller action executes.
  • Authorize: This action filter enables you to restrict access to a particular user or role.

Output Cache :

It saves the output of the method for 10 seconds in a cache.

[OutputCache(Duration =10)]
public string Index()
{
    return DateTime.Now.ToString("T");
}

Handle Error:

If any error occurs while executing the action, it returns the error page and shows the error to the user.

[HandleError]
public ActionResult Index()
{
    throw new NullReferenceException();
}

Authorize:

It allows only authorized users to access the method.

[Authorize]
public ActionResult Index()
{
    return View();
}

Result Filters :

Result filters are executed before or after generating the result for an action. The Action Result type can be ViewResult, PartialViewResult, and RedirectToRouteResult, which derives from the ActionResult class.

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

Exception Filters :

Exception filters are run only if an exception occurs when running any action. below interface is used for that.

Public interface IExceptionFilter  
{  
    void OnException(ExceptionContextfilterContext);  
} 

The below method invokes an exception.

public void OnException(ExceptionContext filterContext)
{
    if (!filterContext.ExceptionHandled && filterContext.ExceptionisArgumentOutOfRangeException)
    {
        filterContext.Result = new RedirectResult("~/Content/RangeErrorPage.html");
        filterContext.ExceptionHandled = true;
    }
}

I hope this article will help you to understand filters and how useful in web applications, how can be used in MVC applications, and also what is the advantages of MVC filters. We will be happy to help you if you have any issues or queries. Comment your suggestions and issues and we will try to resolve them.

What is your reaction?

0
Excited
1
Happy
0
In Love
0
Not Sure
0
Silly

You may also like

Comments are closed.

More in MVC