We’re diving into an essential topic for anyone working with .NET Web API – Controller Filters. Whether you're a seasoned developer or just starting out, understanding how to effectively use filters can save you time and make your code cleaner and more maintainable.

Controller filters in .NET Web API are a powerful feature that allows you to inject logic before or after the execution of an action method. Think of them as the gatekeepers of your API endpoints, handling tasks like logging, authentication, and error handling, without cluttering your controller actions.
- Authorization Filters: These run before the action method and are used to determine if the current user is authorized to execute the action.
- Action Filters: These can run both before and after the action method, perfect for logging or modifying the result.
- Exception Filters: These handle exceptions thrown by action methods, providing a centralized error handling mechanism.
- Result Filters: These run before and after the action results are executed, ideal for modifying the response.
builder.Services.AddControllers(options =>
{
options.Filters.Add(new AuthorizeFilter());
});
[HttpGet(Name = "GetWeatherForecast")]
[Authorize]
public IActionResult Get()
{
return Ok( Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray());
}
public class CheckAuthFilter : IActionFilter
{
bool State;
public void OnActionExecuted(ActionExecutedContext context)
{
context.HttpContext.Response.Headers.Append("AuthenticationState", State.ToString());
}
public void OnActionExecuting(ActionExecutingContext context)
{
var auth = context.HttpContext.Request.Headers.Authorization;
if (auth.Count != 0)
{
context.HttpContext.Request.Headers["AuthenticationState"] = "true";
State = true;
}
else
{
context.HttpContext.Request.Headers["AuthenticationState"] = "false";
State = false;
}
}
}
builder.Services.AddControllers(options =>
{
options.Filters.Add(new CheckAuthFilter());
});
[HttpGet(Name = "GetWeatherForecast")]
public IActionResult Get()
{
if (!CheckAuthState()) return Unauthorized();
return Ok( Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray());
}
private bool CheckAuthState()
{
var authState = HttpContext
.Request
.Headers["AuthenticationState"]
.FirstOrDefault();
return Convert.ToBoolean(authState);
}
[HttpGet("data")]
[ServiceFilter(typeof(CheckAuthFilter))]
public IActionResult GetData()
{
if (!CheckAuthState()) return Unauthorized();
return Ok("New data");
}
builder.Services.AddScoped<CheckAuthFilter>();
🌟 Get in touch with Netcode-Hub! 📫
- GitHub: Explore Repositories 🌐
- Twitter: Stay Updated 🐦
- Facebook: Connect Here 📘
- LinkedIn: Professional Network 🔗
- Email: Email: business.netcodehub@gmail.com 📧
- Buy Me a Coffee: Support Netcode-Hub ☕️
- Patreon: Support on Patreon 🌟