Timo Korinth

2 Meter, 2 Mark

Change WebAPI REST output format from XML to JSON

| 0 comments

The default output format of a WebAPI webservice is XML. To change this to JSON format, you have to manually remove the media type “application/xml” from the configuration of the supported media types. Otherwise it will always use the default xml media output format.

Default xml service output:

<ArrayOfContact xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Siemens.SiveillanceShellServer.Model">
<Contact>
<Id>1</Id>
<Name>Timo Korinth</Name>
</Contact>
<Contact>
<Id>2</Id>
<Name>Han Solo</Name>
</Contact>
<Contact>
</ArrayOfContact>

JSON output format:

[{"Id":1,"Name":"Timo Korinth"},{"Id":2,"Name":"Han Solo"}]

To change this, add these two lines to your server configuration:

var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

The complete server code could look like this:

class Program
{
    static readonly Uri _baseAddress = new Uri("http://localhost:60064/");
 
    static void Main(string[] args)
    {
        // Set up server configuration
        HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);
 
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
 
        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
 
        // Create server
        var server = new HttpSelfHostServer(config);
 
        // Start listening
        server.OpenAsync().Wait();
        Console.WriteLine("Web API Self hosted on " + _baseAddress + " Hit ENTER to exit...");
        Console.ReadLine();
        server.CloseAsync().Wait();
    }
}

Leave a Reply