문제

I have an ASP.Net Web API project which already contains controllers to return result in JSON format. Now I have to add new controllers which should receive and return only XML. I know that I can use the following option to push controllers to return XML serialized objects:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true

But, if I do it, I expect that the old controllers will also return data in XML format, right? This not what I need. So, how can I achieve my goal and return XML serialized objects only from some of controllers? Thank you.

UPDATE

I have tried suggested approach, but it does not work for me. I am testing using Fiddler. Please pay attention that result is still JSON (the last screenshot) Here is additional information:

Controller:

Controller

Request class:

Request class

Response class:

Response class

Request in Fiddler:

Request in Fiddler

Response in Fiddler:

Response in Fiddler

도움이 되었습니까?

해결책

Content negotiation or serialization is not something that controllers should be concerned about.

Out of the box ASP.NET Web API can return both XML and JSON content, the client may request certain format by setting Accept HTTP header.

Set it to:

Accept: application/json

if you want to get JSON back

Accept: application/xml

if you want to get XML back

EDIT: Also note that Web API by default uses DataContractSerializer, answering questions in your comments:

[DataContract(Namespace = "schemas.datacontract.org/2004/07/Test.Models" )]
public class TheThing
{
    [DataMember]
    public string Name { get; set; }
    [DataMember(Name = "contentname")]
    public string ContentName { get; set; }
}

다른 팁

I have run across a few APIs that the Accept does not work. I have found on those APIs if Accept is not working for if I set "Content-Type" header to

Content-Type: application/xml

This will cause the controller to respond in kind with a XML response.

It does appear that in Webapi2 the Accept header does now cause the controller to return the expected application/xml response. This may have been a problem with earlier version of the WebAPI.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top