2012-12-01 62 views
13

是否有可能从ASP.NET Web API而不是XML返回默认的json?默认情况下使用ASP.NET Web API返回json

+1

这种打破了保持web api不可知的模式。如果您在ajax请求的标头中发送“Accept:application/json”,则WebAPI将在Json中响应。我可以看到你的ajax请求吗? – gideon

+0

谢谢队友。这就是我需要的。我刚刚使用web api和api url路径看到了一个来自pluralsight的视频教程,并且它在浏览器中直接响应了json。所以没有Ajax请求。它只是网站/api/control –

+0

你甚至不需要Accept头。如果您在GET请求中没有Accept标头,则应该从WebAPI返回JSON。 –

回答

18

这是默认情况下完成的。 JsonMediaTypeFormatter已注册为第一个MediaTypeFormatter,如果客户端未以特定格式请求响应,则ASP.NET Web API管道会以application/json格式向您提供响应。

如果你想要的是仅支持application/json,删除所有其他格式化,只留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); 
} 
+0

这对我很有用。谢谢 –

8

@ tugberk的解决方案并没有真正完成更改默认格式化的目标。它只是让JSON 只有选项。如果你想JSON默认值,还支持所有其他类型的,你可以做到以下几点:

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); 
} 

注:JSON是默认格式为Web API 2.0。

+0

适合我。好多了。 – Phil