2

I used MVC4 Rest APi for my latest project. But I ran into one issue which I'm unable to figure out.

My request supports both JSON and XML format and I have no problem in getting a response from my request.

While testing I found out issue that while hitting this API using "Advanced Rest Client", even if I send request in JSON format, the response is always in XML format.

But if I use Fiddler, it works fine i.e JSON request gives JSON response and XML request gives XML response

Request headers 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
Content-Type: application/xml 
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8


Response headers 
Cache-Control: no-cache 
Pragma: no-cache 
Content-Type: application/json; charset=utf-8 
Expires: -1 
Server: Microsoft-IIS/8.0 
Date: Mon, 21 Jul 2014 12:01:27 GMT 
Content-Length: 340 

I'm afraid the end users might face the same issue. So is there any way to fix this?

All I can find is to forcefully use only one format for my Web API to solve this. But I have to support both formats.

Is there a way to this?

Thanks

1 Answer 1

4

The Content-Type header of a request does not dictate the type of response from the server, it's used to determine the request type.

The Web API uses content negotiation to determine the media type of the response, specifically the Accept header. To ensure an XML response you will need to set the Accept header like

Accept: application/xml;
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, I read about that but ideally I want to respond a JSON request with JSON response and a XML request with an XML response. I don't want to force a XML response even to a JSOn request. Is it possible?
@hellrokr the response type can be determined by other factors of the request i.e. if you omit the Accept header and provide an XML body it should respond with XML (same with JSON).
Accepting this as answer but this does not work. I had to use Accept: application/xml. Adding "/", again returns the response in JSON. You can try it out in your browser.
@hellrokr */* must take priority if that's the case (although I would have thought order dictated that). Regardless, that was an example, the answer was more about using the Accept header (i've updated the answer anyway).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.