【问题标题】:Retrieving body of json Object of an http Request C#检索http请求C#的json对象的主体
【发布时间】:2018-02-11 15:17:01
【问题描述】:

我有一个问题,我无法检索 JSON 对象的 POST 语句的正文。这是执行http-Request时调用的函数:

        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "HttpTriggerCSharp/name/{name}")]HttpRequestMessage req, string name, TraceWriter log)
    {
        log.Info("C# HTTP trigger function processed a request.");

        string output = JsonConvert.SerializeObject(req.Content.ToString());

        // Fetching the name from the path parameter in the request URL
        return req.CreateResponse(HttpStatusCode.OK, output);

    }

我正在使用 Postman 和以下 URL 执行 POST:http://localhost:7071/api/HttpTriggerCSharp/name/test

在 Header 中我写了“Content-Type: application/json”,Body 看起来像这样:

  {  
   "Benutzer":"Nenad",
   "Passwort":"test"
  }

我的结果是这样的:"\"System.Net.Http.StreamContent\""

感谢您的帮助!

【问题讨论】:

  • 我认为你应该使用httpResponse.Content.ReadAsString();
  • 您必须先将您的流读入一个字符串,然后将流直接提供给序列化器

标签: c# json httprequest body-parser


【解决方案1】:

谢谢大家的回答,

我现在在朋友的帮助下找到了另一个解决方案,如下:

        public static async System.Threading.Tasks.Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "HttpTriggerCSharp/name/{name}")]HttpRequestMessage req, string name, TraceWriter log)
    {
        log.Info("C# HTTP trigger function processed a request.");

        dynamic dataArray = await req.Content.ReadAsAsync<object>();

        string output = dataArray.ToString();

        var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Benutzer>(output);

        // Fetching the name from the path parameter in the request URL
        return req.CreateResponse(HttpStatusCode.OK, data);

    }

【讨论】:

    【解决方案2】:

    Content 是 HttpContent 类的一个实例(正如您在输出中看到的那样)。所以你必须使用适当的方法来获取字符串。

    【讨论】:

      猜你喜欢
      • 2014-01-25
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 2018-10-30
      • 2014-05-17
      • 2020-02-11
      • 2011-05-27
      • 1970-01-01
      相关资源
      最近更新 更多