Action Filter in ASP.NET Core

MAkif DERE
2 min readDec 9, 2020

In this article, I’ll write about the filters, especially action filters in the ASP.NET Core. They are very helpful to manage the project and provide more reusable codes. Some of the most preferred filters are:

- Authorization Filters
- Exception Filters
- Resource Filters
- Result Filters
-
And, Action Filters

In our project, the IT manager wanted to restrict users to send requests for some controllers more than 10 times in a minute. But, the boss did not want to pay for a bot detection system. And reCAPTCHA was not wanted by the art director. Then we began to write the code of the count of requests of each IP address of users and store them in the cache, Redis.

Here, I won’t share the whole project of course. Let say, check IP addresses of requests and give permission to only selected ones. We’ll write a PermissionFilter class:

using Microsoft.AspNetCore.Mvc.Filters;public class PermissionFilter : ActionFilterAttribute

Then we’ll override the OnActionExecuting method to catch the request before the controller.

public override void OnActionExecuting(ActionExecutingContext context)
{
}

In that method, we are checking the IP address, and if it is not validated, we will throw an error message.

var RemoteIpAddress = context.HttpContext.Connection.RemoteIpAddress.ToString();if (RemoteIpAddress != "78.183.118.159")
throw new Exception("No Auth!");

Now, we’ll write a very simple customized exception filter too.

using Microsoft.AspNetCore.Mvc.Filters;public class ExceptionFilter : ExceptionFilterAttribute
{
}

In this class, we are overriding the OnException method to show a JSON.

public override void OnException(ExceptionContext context)
{
context.Result = new ObjectResult(new ErrorModel()
{
Message = context.Exception.Message
});
}

Finally, we can use both the permission filter and the exception filter on our controller which serves top-secret weather forecast data.

[ApiController]
[Route("[controller]")]
[PermissionFilter]
[ExceptionFilter]
public class WeatherForecastController : ControllerBase
{
}

You can see the GitHub repository about this story.

--

--