c# - Request.CreateResponse 与response.Content?

标签 c# httpresponse

我的代码是

var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(
                             JsonConvert.SerializeObject(data),
                             Encoding.UTF8, "application/json");
return response;

通过返回一些 json 数据它可以正常工作。

后来我注意到Request.CreateResponse()可以接受第二个参数T value,其中value的内容HTTP 响应消息。所以我尝试将上面三行压缩成一行

return Request.CreateResponse(
             HttpStatusCode.OK, new StringContent(JsonConvert.SerializeObject(data), 
             Encoding.UTF8, "application/json"));

但它没有按预期工作。它返回

{
  "Headers": [
    {
      "Key": "Content-Type",
      "Value": [
        "application/json; charset=utf-8"
      ]
    }
  ]
}

我是否误解了Request.CreateResponse()的第二个参数?

最佳答案

Did I misunderstand the second parameter of Request.CreateResponse()

是的,你有。第二个参数只是值本身。您将 StringContent 作为 T 值 传递,而不是让 CreateResponse 使用您传递的正确内容类型将其序列化。您看不到数据的原因是 CreateResponse 可能不了解如何正确序列化 StringContent 类型的对象。

您所需要的是:

return Request.CreateResponse(HttpStatusCode.OK, data, "application/json"));

关于c# - Request.CreateResponse 与response.Content?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31630093/

相关文章:

javascript - JavaScript 中相当于 DateTime.Ticks

c# - 解析json文件以获取数据

c# - 如何获取 NHibernate 中的连接标准计数

android - 从 HttpResponse 中提取消息正文

http - 最适合 "job in progress"的 HTTP 状态代码

用于链接操作的 Struts2 ActionContext 和 Response

c# - 如何从备份文件中解码 MySql blob?

c# - 使用 LINQ 连接字符串

python - 在python 3.1中将google搜索结果转换为json

angularjs - 带有 $httpProvider 和 Promise 的 Angular.js 代码。它有什么作用?