Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get back Request Body within ActionFilter

For logging purposes, I am trying to monitor the requests being made through a WebAPI. I have created and I am looking for a way to get back the body sent through in a request after the request has been fulfilled and responded to. I am trying to do this through using a ActionFilter but thus far have failed in reading the body from the request.

Can anybody give some advice how I may access this information?

For context I am trying to do this within this code:

    public class LoggingActionFilter : ActionFilterAttribute
    {
        public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            var test = actionExecutedContext.Request.Content.ReadAsStringAsync().Result;

            return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
        }
    }

I have tried reading back the Content on the actionExecutedContext variable in order to get back the body but have found this to return just blank so far.

like image 960
Jono_2007 Avatar asked Dec 03 '14 02:12

Jono_2007


Video Answer


1 Answers

you're just dealing with request body so don't need to use OnActionExecutedAsync method, you can just override OnActionExecuting like this,

public override void OnActionExecuting(HttpActionContext actionContext)

   {
       var test = (actionContext.Request.Content as ObjectContent).Value.ToString();
       // your logging code here
   }

Another option available in WebAPI is DelegatingHandler. if you want to log just request body then override SendAsync method,

public class ApiLogHandler : DelegatingHandler
{
 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,          
                                               CancellationToken cancellationToken)
 {
   var requestBody = request.Content.ReadAsStringAsync().Result;
   // your logging code here
   return base.SendAsync(request, cancellationToken);
 }
}

If you decided to choose DelegatingHandler then you need to register that handler to Global message handlers.

like image 185
gunvant.k Avatar answered Oct 22 '22 05:10

gunvant.k