[英]Setting content-encoding and content-type with Amazon API for .NET
[英]Setting content-type for Web API 2 response
我对使用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“文本/纯文本”一起发送-需要与Content-Type为“ application / json”一起发送。 我找不到应该如何更改响应的Content-Type,但是即使我可以对每个请求执行此操作似乎也很麻烦。 是我在这里忽略的更好的方法和某种最佳实践吗?
无需手动填充,您可以执行此操作
var response = Request.CreateResponse(HttpStatusCode.OK, responseData);
return response;
这将返回内容类型为json。
您可以通过修改global.asax中的集合来为每个请求设置内容协商
您是否在global.asax中设置了JsonFormatter? 例如:
GlobalConfiguration.Configuration.EnsureInitialized();
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();
我发现的另一个问题是,您在Controller上带有参数签名的路由前缀/路由无法与您传递的通常提供404代码的网址相匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.