Enhancing API Monitoring: Utilizing Action Filters for Comprehensive Logging of Requests and Responses Using C#

Enhancing API Monitoring: Utilizing Action Filters for Comprehensive Logging of Requests and Responses Using C#

Action Filters are a feature of ASP.NET MVC and ASP.NET Core MVC frameworks used to add pre-processing and post-processing logic to controller actions. They allow you to execute code before and after an action method is executed, as well as intercept the action method's return value and exceptions. Action Filters are commonly used for implementing cross-cutting concerns such as logging, authentication, authorization, caching, validation, and more.

Recently, I encountered a need to log each API request received, as well as the corresponding result that was sent back. I ended up logging the incoming JSON, controller name, endpoint, timestamp, and ip address of the caller. In addition to the request, I also logged the response JSON, timestamp, HTTP status code, and message that was returned to the user. With this Action Filter, I save the exact details of each request / response. I chose to store the data in SQL Server, however you can store it any place you would like.


Let's take a look at the main parts of required to create your own Action Filter.

Create Action Filter Class

Your custom Action Filter class simply needs to implement the IActionFilter interface.

public class ApiLogActionFilter : IActionFilter
{
}        


OnActionExecuting Method

You need to implement the OnActionExecuting Method. Code in this method runs BEFORE the code in your controller.

public class ApiLogActionFilter : IActionFilter
{
     public void OnActionExecuting(ActionExecutingContext filterContext)
     {
          //code executes before controller
     }
}
        


OnActionExecuted Method

You need to implement the OnActionExecuted Method. Code in this method runs AFTER the code in your controller.

public class ApiLogActionFilter : IActionFilter
{
     public void OnActionExecuted(ActionExecutedContext filterContext)
     {
     }

     public void OnActionExecuting(ActionExecutingContext filterContext)
     {
          //code executes before controller
     }
}        


Decorate The Controller

To use the Action Filter, you need to either decorate at the controller level (all methods would use the Action Filter), or at the method level (only decorated methods use the Action Filter)

//decorate at the controller level
[ApiController]
[ServiceFilter(typeof(ApiLogActionFilter))]
[Route("api/[controller]")]
public class DemoController : ControllerBase
{
}

OR

//decorate at the method level
[HttpPost]
[ServiceFilter(typeof(ApiLogActionFilter))]
public async Task<IActionResult> Post([FromBody] DemoRequestData demoRequestData)
{
}        


Conclusion

Action Filters provide a flexible and reusable mechanism for adding cross-cutting concerns to controller actions in ASP.NET MVC and ASP.NET Core MVC applications, helping to improve code maintainability, reusability, and separation of concerns. They are easy to implement, require very little code, and give you full control over before and after request tasks.


Donnie Wishard is a passionate and results-driven technology leader with over 20 years of hands-on experience in software architecture, development, management, and consulting. Connect with Donnie on LinkedIn!



Dan Del Savio

Principal Software Developer, Team Lead

1 年

Cool DW. How do you set the log level (Trace, Debug..etc)?

要查看或添加评论,请登录

Donnie W.的更多文章

社区洞察

其他会员也浏览了