0

In my ASP.NET project, all WebApi reply with a json. For this reason in WebApiConfig.cs I set

config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());

Now, I have to change only one webapi to returns XML based on the request in the header.

What is the best practice for that? Is there any example?

1
  • You should read about content negotiations in web API Commented Jul 20, 2018 at 13:18

2 Answers 2

1

enter image description hereadd this to your config :

config.Formatters.XmlFormatter.UseXmlSerializer = true;

then you have xml and json serialization together at the same time , when you set accept header of request to "application/xml , xml/text" then you get xml and if you set header to "application/json , json/text" then you get json result it's called content negotiation

other approach is to serialize the object to xml in the specific method

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

Comments

0

Based on your comment, I updated WebApiConfig.cs:

public static void Register(HttpConfiguration config)
{
    config.Formatters.Clear();
    config.Formatters.Add(new JsonMediaTypeFormatter());
    config.Formatters.Add(new XmlMediaTypeFormatter());
    config.Formatters.XmlFormatter.UseXmlSerializer = true;
}

Then in the webapi where I want to reply with XML

public HttpResponseMessage GetCollections(int Id)
{
    List<CollectionDTO> result = _collectionsLogic.GetCollections(Id);

    IContentNegotiator negotiator = this.Configuration.Services.GetContentNegotiator();

    ContentNegotiationResult resultFormatted = negotiator.Negotiate(
            typeof(List<CollectionDTO>), this.Request, this.Configuration.Formatters);

    if (result == null)
    {
        var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
        throw new HttpResponseException(response);
    }

    return new HttpResponseMessage()
    {
        Content = new ObjectContent<List<CollectionDTO>>(
                      result,
                      resultFormatted.Formatter,
                      resultFormatted.MediaType.MediaType
        )};
    }
}

If I call this webapi with Postman, for example, and I insert in the header Accept equals application/xml, I receive the result in XML format, otherwise in json

Comments

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.