【问题标题】:Setting content-type for Web API 2 response为 Web API 2 响应设置内容类型
【发布时间】:2014-06-19 05:38:50
【问题描述】:

对于为我使用 Web API 2 构建的 RESTful API 返回响应的最合适方式,我感到非常困惑。

起初我让我的操作返回IHttpActionResult,并在我将使用return Ok()或return NotFound()等的方法中。

然后我发现没有Forbidden() 所以我想我一定是做错了。所以现在我让我的行动返回HttpResponseMessage。在我的代码中,我通过执行以下操作返回响应:

HttpResponseMessage response = Request.CreateResponse();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StringContent(JsonConvert.SerializeObject(responseData));
return response;

问题是,这个响应现在使用 Content-Type “text/plain” 发送 - 它需要使用 Content-Type “application/json” 发送。我找不到我应该如何更改响应的 Content-Type,但即使我可以,对每个请求都执行此操作似乎很麻烦。是一种更好的方法,某种我在这里忽略的最佳实践吗?

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-web-api2


    【解决方案1】:

    您可以这样做,而不是手动填充它

    var response = Request.CreateResponse(HttpStatusCode.OK, responseData);
    return response;
    

    这,这将返回内容类型为 json。

    【讨论】:

    • 我写了自己的答案,然后意识到它与你的几乎相同...... Request.CreateResponse 确实将它从 text/plain 更改为 application/json (或者更确切地说,它使用媒体格式化程序)。我会在找到答案的地方添加此链接:Action Results in Web API 2
    【解决方案2】:

    您可以通过修改 global.asax 中的集合来为每个请求设置内容协商

    【讨论】:

      【解决方案3】:

      您是否在 global.asax 中设置了 JsonFormatter?例如:

      GlobalConfiguration.Configuration.EnsureInitialized();
      GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();
      

      我发现的另一个问题是,您的控制器上带有参数签名的路由前缀/路由与您传递的通常提供 404 代码的 Url 不匹配。

      【讨论】:

        猜你喜欢
        • 2015-03-10
        • 2021-04-20
        • 2011-07-26
        • 2015-10-15
        • 2019-03-03
        • 2012-04-20
        • 1970-01-01
        • 2017-06-16
        • 1970-01-01
        相关资源
        最近更新 更多