One of the key extensibility features of ASP.NET MVC is the Filter pipeline, which lets developers insert custom logic before or after action methods are executed.
🔍 What is a Filter in ASP.NET MVC?
A filter in ASP.NET MVC is a custom class used to execute logic at different stages of the request processing pipeline. Filters can be applied to:
- Controllers
- Action Methods
- Globally (via FilterConfig.cs)
Filters are commonly used for:
- Logging
- Caching
- Authorization
- Exception Handling
🧩 Types of Filters in ASP.NET MVC
Here are the main filter types:
✅ 1. Authentication Filters
These filters validate the identity of the user before any authorization logic is performed.
csharp
CopyEdit
public class CustomAuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
// Custom logic for authentication
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) { }
}
✅ 2. Authorization Filters
Authorization filters restrict access to action methods based on user roles or permissions.
csharp
CopyEdit
[Authorize(Roles = "Admin")]
public ActionResult AdminOnly()
{
return View();
}
✅ 3. Action Filters
These filters run before and after an action method is executed.
csharp
CopyEdit
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Logic before action executes
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Logic after action executes
}
}
Apply to controller or method:
csharp
CopyEdit
[LogActionFilter]
public class HomeController : Controller
{
public ActionResult Index() => View();
}
✅ 4. Result Filters
These filters run before and after a view result is processed.
csharp
CopyEdit
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
// Logic before viewing the result
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
// Logic after view the result
}
✅ 5. Exception Filters
Used to handle unhandled exceptions thrown by actions or views.
csharp
CopyEdit
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// Log exception
filterContext.ExceptionHandled = true;
filterContext.Result = new ViewResult { ViewName = "Error" };
}
}
📌 How to Apply Filters in ASP.NET MVC
Filters can be applied in three ways:
Scope How to Apply
Global Add to GlobalFilters.Filters in FilterConfig.cs
Controller Add attribute above controller class
Action Method Add attribute above action method
csharp
CopyEdit
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute()); // global filter
}
}
🔧 Creating a Custom Action Filter
To create your own action filter, inherit from ActionFilterAttribute or implement IActionFilter.
csharp
CopyEdit
public class MyCustomFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Custom pre-processing logic
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Custom post-processing logic
}
}
🧠 Benefits of Using Filters
- Centralised cross-cutting concerns
- Reusable and modular code
- Cleaner and more maintainable controller logic
- Supports dependency injection
❓ FAQs – ASP.NET MVC Filters
1. What are filters in ASP.NET MVC?
Filters allow developers to execute custom logic before or after action methods in the MVC request pipeline.
2. Which filter handles exceptions?
The Exception Filter (IExceptionFilter) handles unhandled exceptions thrown by action methods or views.
3. How to apply a filter globally?
Add the filter to the GlobalFilterCollection in FilterConfig.cs.
4. What's the difference between ActionFilter and ResultFilter?
- ActionFilter: Runs before and after an action method.
- ResultFilter: Runs before and after a view result is executed.
5. Can I apply multiple filters to a single action?
Yes, you can chain multiple filters using attributes or configuration.
6. Is it possible to create a custom authorisation filter?
Yes, by implementing IAuthorizationFilter, you can control access based on custom logic.
📝 Final Thoughts
ASP.NET MVC Filters are a powerful feature that help you insert logic across various stages of a request lifecycle. They promote clean architecture and code reusability. Whether you're implementing logging, authorisation, or error handling, filters are essential for building enterprise-level applications.
🔗 Related Reads
- 📚 ASP.NET MVC - Model View Controller
- 🎯 ASP.NET MVC Interview Questions and Answers
- 🌐 Microsoft Docs – ASP.NET MVC Filters
🙌 Connect & Share
If you found this guide helpful, share it with your network!
👨💻 Written by Umesh Mahajan
🔗 Facebook: Umesh Mahajan | Facebook
📘 SoftCodeLearner: ASP.NET MVC Guide- Controllers
ASP.NET MVC Filters Explained: Types, Examples & Custom Filters for Beginners
By
Umesh Mahajan
ASP.NET
🛡️ ASP.NET MVC Filters – Complete Guide for Beginners
ASP.NET MVC 5 is a powerful web framework based on the Model-View-Controller (MVC) architecture. It enables fast development, test-driven design (TDD), and clean separation of concerns.
No comments:
Post a Comment