2

I am trying to create Audit logs for every controller so that I can keep track of invoked Actions. I am using .net core and Castle Core Dynamic Proxy.

class AuditInterceptor : IInterceptor
{
    private readonly IAuditingHelper _auditingHelper;

    public AuditingInterceptor(IAuditingHelper auditingHelper)
    {
        _auditingHelper = auditingHelper;
    }

    public void Intercept(IInvocation invocation)
    {
       invocation..Proceed();
       log.info(audit); // elided 
    }
}

How can I intercept every Controller ? I can use Simple injector or Autofac.

The reason I am not interested in Filters is that I have 4500 actions. I dont want to decorate them all.

DarthVader
  • 52,984
  • 76
  • 209
  • 300
  • Do you need all of that (external libraries, etc)? Wouldn't a simple ASP.NET Core middle-ware work for such a simple task? – Camilo Terevinto Jun 20 '18 at 17:03
  • Essentially, I need Audits. In a middleware I can have access to Request and Response. But I need more structure. ie: Class name, method name, parameters. etc. – DarthVader Jun 20 '18 at 17:06
  • What about using IActionFilter? ActionArguments gets you the parameters. – Mark G Jun 20 '18 at 18:12

1 Answers1

3

You could use an action filter for this. You can retrieve useful information about the controller and action being executed from the ActionDescriptor. For example:

public class AuditAttribute : ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext context)
   {
       var actionDescriptor = (ControllerActionDescriptor)context.ActionDescriptor;
       var controllerName = actionDescriptor.ControllerName;
       var actionName = actionDescriptor.ActionName;
       var parameters = actionDescriptor.Parameters;
       var fullName = actionDescriptor.DisplayName;
   }
}

You can register the action filter using an attribute on controllers/actions:

[Audit]
public async Task<IActionResult> Get()
{
}

Or globally (every action) at application startup:

services.AddMvc(c => c.Filters.Add(new AuditAttribute()));
Matheus Lacerda
  • 5,983
  • 11
  • 29
  • 45
Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
  • i have 4500 controller action. There is a reason I am asking for interceptor. My fault, you wouldnt know that. – DarthVader Jun 22 '18 at 07:42
  • 1
    this is not the answer I am looking for. I know what a filter is dear sir. I want interceptor. – DarthVader Jun 26 '18 at 15:50
  • @DarthVader I've explained how you can decorate each action using a global filter so you don't have to decorate them individually in my answer. Action filters are just a technical detail to implement the interception concept. – Henk Mollema Jun 26 '18 at 17:19
  • no they are not. they are decorator not interceptor. – DarthVader Jun 26 '18 at 18:13