简体   繁体   English

设置Web API 2响应的内容类型

[英]Setting content-type for Web API 2 response

I'm really confused about the most appropriate way to return responses for my RESTful API that I'm building using Web API 2. 我对使用Web API 2构建的RESTful API返回响应的最合适方法感到非常困惑。

At first I made my actions return IHttpActionResult and in the method I would use return Ok() or return NotFound() etc. 首先,我使动作返回IHttpActionResult ,在该方法中,我将使用return Ok()return NotFound()等。

Then I found there was no Forbidden() so I thought I must be doing things wrong. 然后我发现没有Forbidden()所以我认为我做错了事情。 So now I'm making my actions return HttpResponseMessage . 因此,现在让我的操作返回HttpResponseMessage In my code I'm returning a response by doing the following: 在我的代码中,我通过执行以下操作返回响应:

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

The problem is, this response now gets sent with the Content-Type "text/plain" - it needs to be sent with the Content-Type of "application/json". 问题是,此响应现在随Content-Type“文本/纯文本”一起发送-需要与Content-Type为“ application / json”一起发送。 I can't find how I'm supposed to alter the Content-Type of the response, but even if I could it seems cumbersome to do this with every request. 我找不到应该如何更改响应的Content-Type,但是即使我可以对每个请求执行此操作似乎也很麻烦。 Is the a better way, some sort of best practice that I'm overlooking here? 是我在这里忽略的更好的方法和某种最佳实践吗?

Instead of populating it manually, you can do this 无需手动填充,您可以执行此操作

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

This, this will return content type as json. 这将返回内容类型为json。

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

Have you set the JsonFormatter in your global.asax? 您是否在global.asax中设置了JsonFormatter? For example: 例如:

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

Another issue which I found is that your routing prefix / route with parameters signature on your Controller cannot be match with the Url you passing in giving usually 404 code. 我发现的另一个问题是,您在Controller上带有参数签名的路由前缀/路由无法与您传递的通常提供404代码的网址相匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM