作为JSON格式的HttpResponseMessage内容

25

我有一个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的内容中。但我感觉还有一种更好的方法。你有什么想法吗?

..将对象序列化为JSON格式,并将其放入HttpResponseMessage的内容中。但我感觉还有一种更好的方法。你有什么想法吗?

1个回答

32

你可以做:

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


谢谢!运行得很好!我被迫将所有内容序列化为JSON :) - gosua

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接