How to force API returns JSON be default

Topics: Web Api
Oct 13, 2011 at 5:11 AM

Hi,

I am trying to force my service returns JSON by default. Right now by default it returns XML. When I am using

WebServiceHostFactory in routing configuration:

 

 

 

RouteTable.Routes.Add(new ServiceRoute("Service1", new WebServiceHostFactory(), typeof(Service1))); 

I can set up default response in web.config, like this:

<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json" />

 

 

 

 

 

 when I use HttpServiceHostFactory

var

 

config = new HttpConfiguration() { EnableTestClient = true

};

 

RouteTable.Routes.Add(new ServiceRoute("api/Service", new HttpServiceHostFactory() { Configuration = config }, typeof(Service1)));

 It looks like standardEndpoint is ignored and XML is dfault response format

 

 

 

 

 

Oct 13, 2011 at 3:29 PM
Edited Oct 13, 2011 at 3:33 PM

Hi,

You can do something like the following to make Json formatter the default:

HttpConfiguration config = new HttpConfiguration();
JsonMediaTypeFormatter jsonFormatter = config.Formatters.JsonFormatter;
config.Formatters.Remove(jsonFormatter);
config.Formatters.Insert(0, jsonFormatter);

Thanks,

Kiran Challa


Oct 13, 2011 at 4:20 PM

Thanks Kiran!!!! It works!!!