26

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?

1 Answer 1

32

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thank u! works fine! i forced to serialize everything to json :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.