Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core Audit Logging

I want to implement audit logging in my .NET Core application. Something like

[HttpPost, Auditing]
public dynamic SomeApiAction()
{
    // API code here
    ... 
}

The Attribute should be able to intercept the API call before and after execution in order to log.

Is there any such mechanism available in .net core as a part of the framework? I don't want to use any third-party component. Please advise.

like image 689
sujoyupadhyay Avatar asked Oct 27 '25 05:10

sujoyupadhyay


2 Answers

You can try Audit.WebApi library which is part of Audit.NET framework. It provides a configurable infrastructure to log interactions with your Asp.NET Core Web API.

For example using attributes:

using Audit.WebApi;

public class UsersController : ApiController
{
    [HttpPost]
    [AuditApi(IncludeHeaders = true)]
    public IHttpActionResult Post()
    {
      //...
    }
}
like image 102
thepirat000 Avatar answered Oct 30 '25 15:10

thepirat000


You can use CustomActionFilter for it like

public class CustomDemoActionFilter : Attribute, IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
       
        var controller = context.Controller as Controller;
        if (controller == null) return;
        var controllerName = context.RouteData.Values["controller"];
        var actionName = context.RouteData.Values["action"];
        var message = String.Format("{0} controller:{1} action:{2}", "onactionexecuting", controllerName, actionName);
        var CurrentUrl = "/" + controllerName + "/" + actionName;

       bool IsExists = false;
       if(CurrentUrl=="/Home/Index")
       {
           IsExists=true;
       }
       else
       {
           IsExists=false;
       }           
      
        if (IsExists)
        {
          //do your conditional coding here.
          //context.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "Index" } });
        }
        else
        {
          //else your error page
            context.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "Error" } });
        }
        //base.OnActionExecuting(context);
    }


    public void OnActionExecuted(ActionExecutedContext context)
    {
      
    }
}

and just use this customactionfilter as attribute over your action method like

[HttpGet]
[CustomHMISActionFilter]
public IActionResult Registration()
{
  //your code here
}

like image 39
Ishwar Gagare Avatar answered Oct 30 '25 14:10

Ishwar Gagare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!