读取Web API 2中的POST请求正文 [英] Read POST Request body in Web API 2

查看:65
本文介绍了读取Web API 2中的POST请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅供学习之用,我使用处理程序记录对Web API 2应用程序的所有http请求。

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对象。我想把页眉和正文都打印出来。此外,我在调试时在"HttpRequestMessage"对象中找不到任何内容。

推荐答案

您应该阅读下面的内容

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

这将记录请求正文。

这篇关于读取Web API 2中的POST请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆