Trong ứng dụng ASP.NET MVC, filters có thể áp dụng ở ba level:
- Action Method Level
- Controller Level
- Global Level
Action Method Level
Filters áp dụng ở Action Method level chỉ hoạt động cho action method đó cụ thể.
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers {
public class HomeController : Controller {
[Authorize] // Action Method Level
public string Index() {
return "Index Invoked";
}
}
}
Controller Level
Controller level filters áp dụng cho tất cả action methods của controller đó. Filter dưới áp dụng cho tất cả actions của HomeController, không ảnh hưởng controller khác.
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers {
[Authorize] // Controller Level
public class HomeController : Controller {
public string Index1() {
return "Index1 Invoked";
}
public string Index2() {
return "Index2 Invoked";
}
}
}
Global Level
Global level filters đăng ký trong event Application_Start của global.asax.cs dùng FilterConfig.RegisterGlobalFilters(). Global filters áp dụng cho tất cả controllers và action methods của ứng dụng.
public class MvcApplication : System.Web.HttpApplication {
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
public class FilterConfig {
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
}
}
Thứ tự thực thi Filter (Order of Execution)
Khi request đến, filters chạy theo thứ tự:
- Global Filters (Authorization → Action → Result → Exception)
- Controller Filters (Authorization → Action → Result → Exception)
- Action Filters (Authorization → Action → Result → Exception)
Trong cùng level: Authorization → Action → Result → Exception
Các loại Filter trong ASP.NET MVC
| Filter Type | Interface | Attribute Base Class | Mục đích |
|---|---|---|---|
| Authorization | IAuthorizationFilter | AuthorizeAttribute | Check permissions, authentication |
| Action | IActionFilter | ActionFilterAttribute | Pre/Post action execution logic |
| Result | IResultFilter | ActionFilterAttribute | Pre/Post result execution (view rendering) |
| Exception | IExceptionFilter | HandleErrorAttribute | Handle unhandled exceptions |
Custom Filter Example
// Action Filter - Log trước/sau action
public class LogActionFilter : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
// Trước action
Log($"Action executing: {filterContext.ActionDescriptor.ActionName}");
}
public override void OnActionExecuted(ActionExecutedContext filterContext) {
// Sau action
Log($"Action executed: {filterContext.ActionDescriptor.ActionName}");
}
}
// Áp dụng ở các level
[LogActionFilter] // Action level
public ActionResult Index() { ... }
[LogActionFilter] // Controller level - all actions
public class HomeController : Controller { ... }
// Global level - RegisterGlobalFilters
filters.Add(new LogActionFilter());
Override Filter ở Level thấp hơn
[Authorize] // Global hoặc Controller level
public class AdminController : Controller {
[AllowAnonymous] // Override: cho phép anonymous access action này
public ActionResult Login() { ... }
[Authorize(Roles = "SuperAdmin")] // Override: yêu cầu role mạnh hơn
public ActionResult DeleteUser(int id) { ... }
}
ASP.NET Core - Filters
Trong ASP.NET Core, filters tương tự nhưng đăng ký khác:
// Global (Startup.cs)
services.AddControllers(options => {
options.Filters.Add(); // Type-based
options.Filters.Add(new AuthorizeFilter()); // Instance-based
});
// Controller/Action - Attribute based (giống MVC 5)
[ServiceFilter(typeof(LogActionFilter))]
public class HomeController : Controller { ... }
[TypeFilter(typeof(LogActionFilter))]
public IActionResult Index() { ... }