C# HttpResponseMessage 内容为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14877524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:19:16  来源:igfitidea点击:

Content of HttpResponseMessage as JSON

c#asp.net-mvcjsonasp.net-web-api

提问by gosua

I have an ASP.NET MVC WEB API. For several reasons (redirect because of no authorizations ..), I can't just use a simple object and return it in my controller method. Therefore I need the HttpResponseMessage class which allows me to redirect.

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

Currently I'm doing this:

目前我正在这样做:

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

.. to get the object, serialized as JSON, into the content of HttpResponseMessage. Somehow, I have the feeling that there is another, better, way to do this. Any ideas on that?

.. 将序列化为 JSON 的对象放入 HttpResponseMessage 的内容中。不知何故,我觉得还有另一种更好的方法可以做到这一点。对此有何想法?

采纳答案by Matt Randle

You can do:

你可以做:

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

By default, Web API will set the format of the response based on the Content-Type specified in the HTTP request header but there are some overloads on the CreateResponse method where you can specify the type formatter.

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

You can also remove the Web API XML serializer to force all responses to be JSON if that's what you want - off the top of my head I think it's a Formatters.Remove method on HttpConfiguration.

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