我有一个ASP.NET Web 2项目,该项目已被设置为返回JSONP (使用来自GitHub (https://github.com/WebApiContrib)的ASP.NET Web配置),现在在通过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时,由于响应中带有回调函数等的开销,它根本无法识别响应数据。
有什么好办法处理这件事吗?
发布于 2017-03-28 13:08:41
这招成功了
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"));
}
https://stackoverflow.com/questions/43067701
复制相似问题