8

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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().Result. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.