如何在HttpContent中发布Json并在API控制器中解析它?

时间:2016-11-08 22:03:34

标签: json asp.net-web-api2 httpcontent

我想要获取JSON,将其放在StringContent中并将其传递给我的API。从那里,我想将JSON反序列化回一个类并从那里使用它。目前我收到一个错误,试图反序列化从我可以告诉,到达API时logInfo是空的。当我尝试写出参数时,它在事件日志中是空的。请参阅下面的消费者和API代码。

        public void Log(LogInfo logInfo)
        {
        using (var client = CreateHttpClient())
        {
            var jsonData = JsonConvert.SerializeObject(logInfo);
            HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
            HttpResponseMessage response = client.PostAsync("Logger/Log", content).Result;

            if (!response.IsSuccessStatusCode)
            {
                throw new InvalidOperationException($"{response} was not successful.");
            }
        }
    }


        [HttpPost]
    public HttpResponseMessage Log([FromBody] string logInfo)
    {
        //var logData = JsonConvert.DeserializeObject<LogInfo>(logInfo);
        EventLog.WriteEntry("TestApp", logInfo);
        EventLog.WriteEntry("TestApp", Request.Content.ReadAsStringAsync().Result);
        //Log(logData);

        return Request.CreateResponse(HttpStatusCode.OK);
    }

1 个答案:

答案 0 :(得分:1)

您的控制器方法Log应该采用LogInfo参数。此LogInfo模型是充当DTO / POCO的类。所以它应该只包含你想要收集的属性(getter和setter)。然后,您可以将此DTO / POCO映射到您的业务领域模型。

  [HttpPost]
public HttpResponseMessage Log(LogInfo logInfo)
{
   ...
}