8

I understand that WEB API uses content negotiation for Accept - Content-Type to return json or xml. This is not good enough and I need to be able pragmatically decide if I want to return json or xml.

The internet is flooded with obsolete examples of using HttpResponseMessage<T>, which is no longer present in MVC 4.

    tokenResponse response = new tokenResponse();
response.something = "gfhgfh";

    if(json)
    {
        return Request.CreateResponse(HttpStatusCode.OK, response, "application/json");
    }
    else
    {
         return Request.CreateResponse(HttpStatusCode.OK, response, "application/xml");
    }

How do I change the above code so that it works?

1 Answer 1

23

Try like this:

public HttpResponseMessage Get()
{
    tokenResponse response = new tokenResponse();
    response.something = "gfhgfh";

    if(json)
    {
        return Request.CreateResponse(HttpStatusCode.OK, response, Configuration.Formatters.JsonFormatter);
    }
    else
    {
         return Request.CreateResponse(HttpStatusCode.OK, response, Configuration.Formatters.XmlFormatter);
    }    
}

or even better, to avoid cluttering your controller with such plumbing infrastructure code you could also write a custom media formatter and perform this test inside it.

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

2 Comments

Right! My mistake was that Get() method had a return type of tokenResponse. Thanks!
Any standard class that could replace tokenResponse in this example?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.