I want to create a filter in MVC project which logs activity of each and every controller action. I am just injecting an object of type ILogger using which I am logging the logs in my Azure table storage.
This blog shows how to create action filter and how we can add it globally or in any controller or in any action.
Create an Action filter class:
- namespace Filter {
- using System;
- using Microsoft.AspNetCore.Mvc.Filters;
- using Microsoft.AspNetCore.Routing;
- using Core.Logging;
-
-
-
-
- [AttributeUsage(AttributeTargets.Class)]
- public class LogActionFilterAttribute: ActionFilterAttribute {
- private readonly ILogger logger;
-
-
-
-
- public LogActionFilterAttribute(ILogger logger) {
- this.logger = logger;
- }
-
-
-
-
- public override void OnActionExecuting(ActionExecutingContext context) {
- this.Log("OnActionExecuting", context.RouteData);
- base.OnActionExecuting(context);
- }
-
-
-
-
-
- public override void OnActionExecuted(ActionExecutedContext context) {
- this.Log("OnActionExecuted", context.RouteData);
- base.OnActionExecuted(context);
- }
-
-
-
-
- public override void OnResultExecuting(ResultExecutingContext context) {
- this.Log("OnResultExecuting", context.RouteData);
- base.OnResultExecuting(context);
- }
-
-
-
-
- public override void OnResultExecuted(ResultExecutedContext context) {
- this.Log("OnResultExecuted", context.RouteData);
- base.OnResultExecuted(context);
- }
-
-
-
-
-
- private void Log(string methodName, RouteData routeData) {
- var controllerName = routeData.Values["controller"];
- var actionName = routeData.Values["action"];
- string message = $ "MethodName :{methodName} , controller:{controllerName} , action:{actionName}";
- this.logger.log(message);
- }
- }
- }
How to make any controller to use this action filter:
Method 1
If you want the functionality to enable for all controllers by default
In starup.cs write the below line:
- services.AddMvc(options =>
- {
- options.Filters.Add(typeof(LogActionFilterAttribute));
- });
Method 2
If you want to use it in Controller specifically:
In starup.cs write the below line:
- services.AddScoped<LogActionFilterAttribute>();
In Action Method or controller use the below attribute:
- [ServiceFilter(typeof(ExampleFilterWithDI))]