Audit Log Action Filter in MVC

Dheeraj Kumar Gunti

Reading Time : ( words)

Hi All,

Welcome back to Knowledge Base. Hope everyone are doing great.

These days in Application development life cycle, there is one component which is playing an important role that is auditing. There are lot of specifications and processes involved in auditing mechanism. If we take an scenario with respect to using MVC framework, we can add this process in identifying the actions auditing and data auditing.

In this tutorial we will see how can we perform action auditing. We can go with either writing them in a file or database table.

In MVC we have a concept called Filters. There are types which we can go and use them in MVC application like Authorize Filter, Error Filter, Action filter etc. In this scenario of audit logging we will use Action Filter as one way of approach.

Action Filter will execute in two ways, one when action execution starts and another when action execution ends.

Step 1: Create a custom class and name it as AuditLogActionFilter (Example) and inherit this class from ActionFilterAttribute abstract class.

There are multiple methods in ActionFilterAttribute class.

For our scenario we can go with OnActionExecuted and OnActionExecuting. We need to override these methods to accomplish our functionality.

Step 2: Override OnActionExecuted and OnActionExecuting methods.

filterContext object can be used in fetching context related information of the action.

In the above code snippet we are trying to fetch the RouteData information. We can use related properties based on how and what we need to store in the log.

We can indicate to user whether the action executed successfully or not also using the below snippet which we need to add in OnActionExecuted method.

Complete methods look like this (We can extend the process based on our need)

We can use this Filter across all the ActionMethods in our application.

ActionType can be used in making the log more meaningful.

Download the Class File from here.