Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content of HttpResponseMessage as JSON

Tags:

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?

like image 445
gosua Avatar asked Feb 14 '13 14:02

gosua


People also ask

What is JSON object in C#?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is language-independent, easy to understand and self-describing. It is used as an alternative to XML. JSON is very popular nowadays. JSON represents objects in structured text format and data stored in key-value pairs.


1 Answers

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.

like image 169
Matt Randle Avatar answered Sep 17 '22 17:09

Matt Randle