简体   繁体   中英

Content of HttpResponseMessage as JSON

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.

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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