get the request body of all quests before handle it

Posted chucklu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了get the request body of all quests before handle it相关的知识,希望对你有一定的参考价值。

https://stackoverflow.com/questions/23660340/need-to-log-asp-net-webapi-2-request-and-response-body-to-a-database

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers

 拦截api的请求,并进行处理

I would recommend using a DelegatingHandler. Then you will not need to worry about any logging code in your controllers.

public class LogRequestAndResponseHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // log request body
        string requestBody = await request.Content.ReadAsStringAsync();
        Trace.WriteLine(requestBody);

        // let other handlers process the request
        var result = await base.SendAsync(request, cancellationToken);

        if (result.Content != null)
        {
            // once response body is ready, log it
            var responseBody = await result.Content.ReadAsStringAsync();
            Trace.WriteLine(responseBody);
        }

        return result;
    }
}

Just replace Trace.WriteLine with your logging code and register the handler in WebApiConfig like this:

config.MessageHandlers.Add(new LogRequestAndResponseHandler());

 

以上是关于get the request body of all quests before handle it的主要内容,如果未能解决你的问题,请参考以下文章

The process of container handles the servlet request

[React] Create a queue of Ajax requests with redux-observable and group the results.

Most efficient way to get the last element of a stream

Given a matrix, get the number of path from the top left cell to the top right cell.

Failed to load resource: the server responded with a status of 400 (Bad Request)

Failed to load resource: the server responded with a status of 400 (Bad Request) 错误请求解决