在Windows应用程序中处理JSONP响应

时间:2017-03-28 10:56:01

标签: c# asp.net json jsonp

我有一个ASP.NET Web API 2项目,该项目已设置为返回JSONP (使用来自GitHub的ASP.NET Web API Contrib repo(https://github.com/WebApiContrib)),现在,当通过jQuery使用API​​时,我的Web应用程序中的Everything看起来很好用。

但是,还有一个需要访问相同数据的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它只是无法识别响应数据,因为响应中有回调函数等开销。

有没有一种好方法可以解决这个问题?

1 个答案:

答案 0 :(得分:0)

这就是诀窍

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