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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With