0

I have a ASP.NET Web API 2 project that's been set up to return JSONP (using the ASP.NET Web API Contrib repo from GitHub (https://github.com/WebApiContrib)), now Everything looks fine and dandy in my web application when consuming the API via jQuery.

However, there's also a windows application that needs access to the same data, but I'm quite at a loss on how to process the response in the c# class.

I have this code, which worked nicely (using JSON.NET) when the API returned plain JSON:

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

However, using JSONP it simply doesn't recognize that response data due to the overhead stuff with callback functions etc in the response.

Is there a good way of handling this?

JaggenSWE
  • 1,950
  • 2
  • 24
  • 41
  • Good way: make your API optionally return JSON or JSONP (according to GET-parameter or headers). Bad way: something like `jsonData = jsonData.Replace("callback(", ""); jsonData = jsonData.Substring(0, jsonData.Length - 1);` (please, no) – Yeldar Kurmangaliyev Mar 28 '17 at 10:58
  • I was thinking about having that as well, I just started out with WebAPI, With WCF I have it all in my head, but here I just don't know how to get it in Place so that the API will return either plain JSON or JSONP. :P I've googled and tried to read up on how to achieve it, but end up with nothing. – JaggenSWE Mar 28 '17 at 11:13

1 Answers1

0

This did the trick

    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"));
    }
JaggenSWE
  • 1,950
  • 2
  • 24
  • 41
  • Can you please expand this answer a bit - looks like this is server side change and not a client side change (and hence actually may be answering something different). Possibly editing question instead would be better option. As asked question would be duplicate of https://stackoverflow.com/questions/48470971/how-to-deserialize-a-jsonp-response-preferably-with-jsontextreader-and-not-a-st, but based on answer it is about something different. – Alexei Levenkov Jan 29 '18 at 03:39