The ASP.NET Core Pipeline represents the sequence of middleware components that handle incoming HTTP requests and outgoing responses, allowing for custom request processing.
Authorization filters in ASP.NET Core allow you to control access to resources or actions based on user permissions and roles.
Example
[Authorize(Roles = "Admin")]
public IActionResult AdminDashboard()
{
return View();
}
Resource Filter
Resource filters execute before the model binding and can manipulate the model or add additional data to the model.
Example
public class CustomResourceFilter : IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
// Pre-processing logic
}
public void OnResourceExecuted(ResourceExecutedContext context)
{
// Post-processing logic
}
}
Action Filter
Action filters run before and after controller actions, enabling you to modify the request or response context for specific actions.
Example
public class CustomActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// Pre-action logic
}
public void OnActionExecuted(ActionExecutedContext context)
{
// Post-action logic
}
}
Exception Filter
Exception filters catch exceptions thrown during request processing, allowing you to handle errors and provide custom error responses.
Example
public class CustomExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
// Custom exception handling logic
context.Result = new ViewResult { ViewName = "Error" };
context.ExceptionHandled = true;
}
}
Result Filter
Result filters run before and after the action result is executed, making it possible to modify the action result or perform additional actions.
Example
public class CustomResultFilter : IResultFilter
{
public void OnResultExecuting(ResultExecutingContext context)
{
// Pre-result logic
}
public void OnResultExecuted(ResultExecutedContext context)
{
// Post-result logic
}
}
Global Level
Filters configured at the global level apply to all controllers and actions in your ASP.NET Core application.
Controller Level
Filters can be applied at the controller level, affecting all actions within that controller.
Action Level
Filters can be applied at the action level, allowing for fine-grained control over specific actions in your controllers.
Configuring Filters
Filters in ASP.NET Core can be configured in the Startup.cs file using the AddMvc or AddControllers method. Filters can be added and customized during application configuration.