在Web API 2中读取POST请求主体

时间:2018-05-20 07:53:42

标签: c# asp.net-web-api2

出于学习目的,我使用处理程序将所有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;
    }
}

这只是按如下方式打印请求标题:

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主体中发送一个没有打印的json对象。我想打印Headers和body。调试时我也无法在'HttpRequestMessage'对象中找到任何内容。

3 个答案:

答案 0 :(得分:2)

您应该阅读以下内容

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

这将记录请求正文。

答案 1 :(得分:1)

您可以阅读发布请求,如下所示。

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

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

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

上面的代码会对你的应用程序产生性能影响,因为它会针对每个操作调用点击,你需要对此保持谨慎。您可以考虑启用和禁用此标志。

答案 2 :(得分:1)

  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();