Go back Request body in ActionFilter

For logging purposes, I am trying to track requests made through the WebAPI. I created, and I am looking for a way to return the body sent in the request after the request and response have completed. I am trying to do this using an ActionFilter but still have not been able to read the body from the request.

Can someone give some advice on how I can access this information?

In context, I am trying to do this inside 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 tried reading Content in the actionExecutedContext variable to return the body, but found that it was still empty.

+5
source share
1 answer

you just deal with the request body, so you don’t need to use the 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 the WebAPI is the DelegatingHandler . if you want to register only the request body, then override the 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 decide to choose DelegatingHandler , you need to register this handler with Global message handlers .

+4
source

Source: https://habr.com/ru/post/1208200/


All Articles