ASP.NET MVC Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

ASP.NET MVC Filters

Back to: ASP.NET MVC Tutorial

In ASP.NET MVC 5, filters are used to execute custom logic before or after action methods execute. These filters provide a way to intercept various stages of request processing, such as authentication, authorization, action execution, result processing, and error handling. Let's discuss the different types of filters in ASP.NET MVC 5 with examples.

1. Authentication Filters

  • Purpose: Authentication filters run before any other filter or action method to ensure that the user is authenticated.
  • Example: Custom authentication filter to check if a user is logged in.
using System.Web.Mvc;
using System.Web.Mvc.Filters;
public class CustomAuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated == false)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
// Redirect to login if user is not authenticated
if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new RedirectResult("/Account/Login");
}
}
}
  • Usage:
[CustomAuthenticationFilter]
public ActionResult SecureAction()
{
return View();
}

2. Authorization Filters

  • Purpose: Authorization filters execute after authentication and determine whether the user has permission to execute the action.
  • Example: Custom authorization filter to check for specific roles.
using System.Web.Mvc;
public class CustomAuthorizationFilter : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return httpContext.User.IsInRole("Admin");
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult("/Account/AccessDenied");
}
}
  • Usage:
[CustomAuthorizationFilter]
 public ActionResult AdminOnly()
{
return View();
}

3. Action Filters

  • Purpose: Action filters execute before and after the action method is called, allowing you to modify the input parameters or the result.
  • Example: Logging action filter to log action method execution.
using System.Diagnostics;
using System.Web.Mvc;
 public class LoggingActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Debug.WriteLine("Action Executing: " + filterContext.ActionDescriptor.ActionName);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
Debug.WriteLine("Action Executed: " + filterContext.ActionDescriptor.ActionName);
}
}
  • Usage:
[LoggingActionFilter]
public ActionResult Index()
{
return View();
}

4. Result Filters

  • Purpose: Result filters execute before and after the action result is processed, allowing you to modify the result before it’s sent to the client.
  • Example: Custom result filter to add a custom header to the response.
using System.Web.Mvc;
public class CustomResultFilter : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Headers.Add("X-Custom-Header", "MyCustomValue");
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
// Additional logic after result execution if needed
}
}
  • Usage:
[CustomResultFilter]
public ActionResult About()
{
return View();
}

5. Exception Filters

  • Purpose: Exception filters execute when there’s an unhandled exception during the processing of an action, allowing you to handle errors globally.
  • Example: Custom exception filter to log and handle exceptions.
using System.Diagnostics;
using System.Web.Mvc;
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// Log exception details Debug.WriteLine("Exception: " + filterContext.Exception.Message);
// Redirect to error page filterContext.Result = new RedirectResult("/Error/ServerError");
filterContext.ExceptionHandled = true;
}
}
  • Usage:
[CustomExceptionFilter]
public ActionResult ErrorProneAction()
{
throw new Exception("Something went wrong!");
}

Summary Table of ASP.NET MVC 5 Filters

Filter Type Interface Execution Time Example Purpose
Authentication IAuthenticationFilter Before all other filters or action methods Check if user is authenticated
Authorization IAuthorizationFilter After authentication, before action methods Check user roles/permissions
Action IActionFilter Before/After action methods Logging, modifying input parameters
Result IResultFilter Before/After the action result execution Modify result before sending to client
Exception IExceptionFilter On unhandled exceptions Handle/log errors, display error page

Each filter can be applied globally, at the controller level, or to individual actions. This flexibility allows you to tailor the application's flow precisely as needed.

Scroll to Top