Use XML format with ASP.NET Core web APIs

In one of my past articles I discussed how to deal with XML data in ASP.NET Web APIs. Although JSON is quite popular format in API communication, at times you might need to handle XML data. To that end this article describes the required configuration with a simple example.

Let's assume you have an ASP.NET Core API with a simple Get() action as shown below:

As you can see, the Get() action simply returns a list of countries and their codes. The Country class used in the Get() action looks like this:

public class Country
    public string Code { get; set; }
    public string Name { get; set; }

If you invoke this API using Postman, you will get this JSON response:

Now, let's tell the server that we would like to get XML data back rather than JSON. We do this by adding Accept request header as  follows:

We specify the Accept header value to be application/xml.

What's the outcome? The server refuses to return XML and we again get JSON data as shown earlier.

This happens because we haven't told ASP.NET Core that we also want to return XML data. You do this by calling AddXmlSerializerFormatters() in the ConfigureServices(). The following code shows how this is done.

public void ConfigureServices(IServiceCollection services)

We have now configured ASP.NET Core to allow XML in the API response. Let's confirm this by running the Postman again.

As expected now we get XML response.

Let's take this a bit further. What if you want  to make XML as the default response format for an API action? That way you don't need to specify Accept header. You can accomplish this using [Produces] attribute. This is how you use [Produces] attribute on an action.

Run the Postman again and hit the API without any headers. This time you will get XML in the response even without Accept header.

If you want to make XML the default format for multiple actions, you need to decorate all of them with [Produces] attribute.

What if you want to make XML as the default response format for the entire application. This is how you can do it:

This time we added the ProducesAttribute global filter in the ConfigureServices(). Now you don't need to decorate individual actions with [Produces] attribute and you will still get XML in the response.

That's it for now! Keep coding!!

Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a yoga mentor, meditation teacher, and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his private online courses on ASP.NET and meditation go here and here.

Posted On : 18 February 2019

Tags : ASP.NET ASP.NET Core MVC C# Visual Studio