我有一个 ASP.NET Web API 2项目,该项目已被设置为返回JSONP(使用 GitHub (https://github.com/WebApiContrib(的 ASP.NET Web API Contrib 存储库(,现在通过 jQuery 使用 API 时,我的 Web 应用程序中一切看起来都很好。
但是,还有一个 Windows 应用程序需要访问相同的数据,但我对如何处理 c# 类中的响应感到非常茫然。
我有这段代码,当 API 返回纯 JSON 时,它运行良好(使用 JSON.NET(:
public List<DropItem> GetAvailableDomains()
{
string jsonData = null;
using (WebClient wc = new WebClient())
{
jsonData = wc.DownloadString("http://foo.bar/api/core/getavailabledomains");
}
return JsonConvert.DeserializeObject<List<DropItem>>(jsonData);
}
但是,使用 JSONP,由于响应中带有回调函数等的开销,它根本无法识别响应数据。
有没有处理这个问题的好方法?
这成功了
public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
{
var jsonp = new JsonpMediaTypeFormatter(formatters.JsonFormatter);
jsonp.MediaTypeMappings.Add(new QueryStringMapping("type", "jsonp", "application/json"));
GlobalConfiguration.Configuration.Formatters.Add(jsonp);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "json", "application/json"));
}