在 Web API 2 中阅读 POST 请求 body

Read POST Request body in Web API 2

仅出于学习目的,我使用处理程序将所有 http 请求记录到我的 Web API 2 应用程序。

enum LogType {Information = 1, Warning = 2, Error = 3 }
public class LogHandler: DelegatingHandler
{
    async protected override Task SendAsync(HttpRequestMessage httpRequest, CancellationToken cancellationToken)
    {
        Trace.WriteLine(httpRequest.ToString(), LogType.Information.ToString());
        var response = await base.SendAsync(httpRequest, cancellationToken);
        return response;
    }
}

这只是打印请求 Headers 如下:

Information: Method: POST, RequestUri: 'http://localhost:49964/school/title?number=1&name=swanand pangam', Version: 1.1, Content: System.Web.Http.WebHost.HttpControllerHandler+LazyStreamContent, Headers:
{
  Cache-Control: no-cache
  Connection: keep-alive
  Accept: text/csv
  Accept-Encoding: gzip
  Accept-Encoding: deflate
  Host: localhost:49964
  User-Agent: PostmanRuntime/7.1.1
  Postman-Token: 074c3aab-3427-4368-be25-439cbabe0654
  Content-Length: 31
  Content-Type: text/plain
}

但我还在 POST body 中发送了一个 json object,但未打印出来。我想同时打印 Headers 和 body。我在调试时也找不到 'HttpRequestMessage' object 中的任何内容。

您应该阅读以下内容

    // log request body
    string requestBody = await httpRequest.Content.ReadAsStringAsync();
    Trace.WriteLine(requestBody);

这将记录请求正文。

您可以像下面这样阅读 post 请求。

 string requestBody = await request.Content.ReadAsStringAsync();
 var response = await base.SendAsync(httpRequest, cancellationToken);

如果您不想记录已生成的响应,您可以尝试以下操作。

 var responseBody = await response.Content.ReadAsStringAsync();

以上代码将对您的应用程序产生性能影响,因为它会命中每个操作调用,您需要对此保持谨慎。您可以考虑使用一个标志来启用和禁用它。

  var body = new StreamReader(Request.Body);
    //The modelbinder has already read the stream and need to reset the stream index
    body.BaseStream.Seek(0, SeekOrigin.Begin); 
    var requestBody = body.ReadToEnd();