HttpResponseMessage的内容为JSON

本文关键字:JSON HttpResponseMessage | 更新日期: 2023-09-27 17:59:01

我有一个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的内容中。不知怎么的,我觉得还有另一种更好的方法可以做到这一点。对此有什么想法吗?

HttpResponseMessage的内容为JSON

你可以做:

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方法。