繁体   English   中英

HttpResponseMessage的内容为JSON

[英]Content of HttpResponseMessage as JSON

我有一个ASP.NET MVC WEB API。 由于几个原因(由于没有授权重定向..),我不能只使用一个简单的对象并在我的控制器方法中返回它。 因此我需要HttpResponseMessage类,它允许我重定向。

目前我这样做:

var response = new Response { responseCode = Response.ResponseCodes.ItemNotFound };
var formatter = new JsonMediaTypeFormatter();
response.Content = new ObjectContent<Response>(response, formatter, "application/json");

..将序列化为JSON的对象放入HttpResponseMessage的内容中。 不知何故,我觉得还有另一种更好的方法。 有什么想法吗?

你可以做:

var response = new Response { responseCode = Response.ResponseCodes.ItemNotFound };
Request.CreateResponse<Response>(HttpStatusCode.OK, response);

默认情况下,Web API将根据HTTP请求标头中指定的Content-Type设置响应的格式,但CreateResponse方法中存在一些重载,您可以在其中指定类型格式化程序。

您还可以删除Web API XML序列化程序以强制所有响应为JSON(如果这是您想要的) - 我认为它是HttpConfiguration上的Formatters.Remove方法。

暂无
暂无

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

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