Get back Request Body within ActionFilter

14,400

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.

Share:
14,400

Related videos on Youtube

Jono_2007
Author by

Jono_2007

Updated on June 12, 2022

Comments

  • Jono_2007
    Jono_2007 almost 2 years

    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.

  • Jono_2007
    Jono_2007 over 9 years
    I've tried out the OnActionExecuting command but had no luck, it throws a Object reference not set to an instance of an object error. The idea with the delegating handler does work but I was hoping to do it after the request has been fulfilled. Would this be possible?
  • Jono_2007
    Jono_2007 over 9 years
    After changing my function over to using a non Async function as you suggested, I was able to get back the body as I wanted through actionExecutedContext.Request.Content.ReadAsStringAsync().Re‌​sult. Thanks!