json - 如何在 HttpContent 中 POST Json 并在 API Controller 中解析它?

标签 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);
    }

最佳答案

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

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

关于json - 如何在 HttpContent 中 POST Json 并在 API Controller 中解析它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40497207/

相关文章:

c++ - 如何在 C++ 中处理泛型对象

javascript - 在js中创建嵌套Json

c# - 将来自 API 的结果合并到一个对象中

c# - 如何使用 web api 获取资源的可用性?

asp.net-web-api - 使用路由与查询字符串参数是错误的吗?

c# - HttpContent.ReadAsStringAsync 导致请求挂起(或其他奇怪的行为)

c# - 使用 httpClient 发布 json 未到达服务器

python - 用 Python 读取 JSON

javascript - 无效的 JSON 原语 - Asp.Net MVC 4