How to trace each request ASP.NET Web API with NLog How to trace each request ASP.NET Web API with NLog json json

How to trace each request ASP.NET Web API with NLog


That's what you have action filters for...to do something before/after an action method is a executing/executed

public class MyCustomFilter : System.Web.Http.Filters.ActionFilterAttribute{    public override void OnActionExecuting(HttpActionContext actionContext)    {        //Do something here before an action method starts executing    }    public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext context)    {        //Do something here after an action method finished executing    }}

Then, you'll need to plug this filter in the asp.net pipeline...when the application starts, whether you use owin/katana or global.asax it doesn't matter...

GlobalConfiguration.Configuration.Filters.Add(new MyCustomFilter());

The line above will add that filter to all action methods. If you want to turn tracing off for some action methods, simply add a flag/switch property to the action filter so that you can switch tracing off for some actions...

public class MyCustomFilter : System.Web.Http.Filters.ActionFilterAttribute{    public bool DisableTracing{get;set;}    public override void OnActionExecuting(HttpActionContext actionContext)    {        if(!DisableTracing){               //Do something here before an action method starts executing        }    }    public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext context)    {        if(!DisableTracing){               //Do something here before an action method starts executing        }    }}

And now you can turn it of on controller action...

[MyCustomFilter(DisableTracing = true)]public IHttpActionResult MyAction(int id){}

Update

To read the JSON object from the request's body simply read the content of the request as below...

 request.Content.ReadAsStringAsync().Result;


The solution of Leo seems correct for MVC but for Http REST API I had to implement the solution from http://www.c-sharpcorner.com/UploadFile/1492b1/restful-day-sharp6-request-logging-and-exception-handingloggin/

public class HttpLoggingFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute{    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)    {        //Do something here    }    public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)    {        //Do something here    }}

After testing both method on my code I can tell the code from Leo is performed on an page refresh bit not on simple REST request.