Audit.NET and Asp Net Core Razor Pages

777 Views Asked by At

I am using razor pages in my ASP.NET Core application. I need to enable logging with Audit.NET library, it works fine with ASP.NET MVC controllers, but it doesn't work with Razor pages.

Here is an example how I declare a PageModel class with Audit attribute:

[Audit(EventTypeName = "{area}/{Page} ({verb})",
   IncludeResponseBody = true,
   IncludeRequestBody = true,
   IncludeHeaders = true,
   IncludeModel = true)]
public class LoginIndexModel : PageModel
{
  ...
}

It throws NullReferenceException when AuditAttribute action filter is invoked.

Here is the method declared in AuditAttribute:
(As I understand actionDescriptor parameter cannot be casted to ControllerActionDescriptor)

private bool IsActionIgnored(ActionDescriptor actionDescriptor)
{
    if (actionDescriptor == null)
        return false;

    return ((IEnumerable<object>)(actionDescriptor as ControllerActionDescriptor).ControllerTypeInfo
               .GetCustomAttributes(typeof(AuditIgnoreAttribute), true)).Any<object>() || 
           ((IEnumerable<object>)(actionDescriptor as ControllerActionDescriptor).MethodInfo
               .GetCustomAttributes(typeof(AuditIgnoreAttribute), true)).Any<object>();
}

So what can I do in this case? Has anyone encountered a similar problem?

1

There are 1 best solutions below

0
On BEST ANSWER

The audit mechanism for MVC was implemented with an action filter, but action filters are not supported on Razor Pages.

For razor pages, a Page Filter is provided instead, so you can configure the auditing.

Use the provided AuditPageFilter instead of the [Audit] attribute.

Basically you just need to add the filter to the collection on your startup logic, for example:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages()
        .AddMvcOptions(options =>
        {
            options.Filters.Add(new Audit.Mvc.AuditPageFilter()
            {
                IncludeHeaders = true, ...
            });
        });
}

Check the readme here.