Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return json by default using ASP.NET Web API

Is it possible to return json by default from the ASP.NET Web API instead of XML?

like image 825
Wesley Skeen Avatar asked Dec 01 '12 17:12

Wesley Skeen


2 Answers

It's what is done by default. JsonMediaTypeFormatter is registered as the first MediaTypeFormatter and if the client doesn't request the response in a specific format, ASP.NET Web API pipeline gives you the response in application/json format.

If what you want is to only support application/json, remove all other formatters and only leave JsonMediaTypeFormatter:

public static void Configure(HttpConfiguration config) {

    var jqueryFormatter = config.Formatters.FirstOrDefault(x => x.GetType() == typeof(JQueryMvcFormUrlEncodedFormatter));
    config.Formatters.Remove(config.Formatters.XmlFormatter);
    config.Formatters.Remove(config.Formatters.FormUrlEncodedFormatter);
    config.Formatters.Remove(jqueryFormatter);
}
like image 190
tugberk Avatar answered Nov 01 '22 17:11

tugberk


@tugberk's solution doesn't really accomplish the goal of changing the default formatter. It simply makes JSON the only option. If you want to make JSON the default and still support all of the other types, you can do the following:

public static void Configure(HttpConfiguration config) {
    // move the JSON formatter to the front of the line
    var jsonFormatter = config.Formatters.JsonFormatter;
    config.Formatters.Remove(jsonFormatter);
    config.Formatters.Insert(0, jsonFormatter);
}

Note: JSON is the default formatter as of Web API 2.0.

like image 35
Chris Staley Avatar answered Nov 01 '22 18:11

Chris Staley