C# HttpResponseMessage的内容为JSON

C# HttpResponseMessage的内容为JSON,c#,asp.net-mvc,json,asp.net-web-api,C#,Asp.net Mvc,Json,Asp.net Web Api,我有一个ASP.NET MVC WEB API。出于几个原因(因为没有授权而重定向…),我不能只使用一个简单的对象并在我的控制器方法中返回它。因此,我需要HttpResponseMessage类,它允许我重定向 目前我正在这样做: var response = new Response { responseCode = Response.ResponseCodes.ItemNotFound }; var formatter = new JsonMediaTypeFormatter(); resp

我有一个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");
var response=newresponse{responseCode=response.ResponseCodes.ItemNotFound};
var formatter=新的JsonMediaTypeFormatter();
Content=newObjectContent(响应、格式化程序、“应用程序/json”);
。。将序列化为JSON的对象放入HttpResponseMessage的内容中。不知怎的,我觉得还有另一种更好的方法。有什么想法吗

您可以执行以下操作:

var response = new Response { responseCode = Response.ResponseCodes.ItemNotFound };
Request.CreateResponse<Response>(HttpStatusCode.OK, response);
var response=newresponse{responseCode=response.ResponseCodes.ItemNotFound};
Request.CreateResponse(HttpStatusCode.OK,response);
默认情况下,Web API将根据HTTP请求标头中指定的内容类型设置响应的格式,但CreateResponse方法上存在一些重载,您可以在其中指定类型格式化程序


您还可以删除Web API XML序列化程序,以强制所有响应为JSON(如果您需要的话)-我想这是一个格式化程序。删除HttpConfiguration上的方法。

谢谢!很好!我被迫将所有内容序列化为json:)