Search code examples
javascriptjsonangularjsasp.net-web-apijsonp

JSONP response from WebAPI to Angular


I have a simple angular controller like below:

angular.module('widget.controllers', [])
  .controller('ProductController', ['$scope','$http', function ($scope, $http) {

      $http.jsonp('http://localhost:27467/api/Products/GetProducts/EUR?callback=JSON_CALLBACK')
      .success(function (data) {
          console.log(data);
      });

  }]);

along with a simple action in web api controller:

[HttpGet]
public HttpResponseMessage GetProducts(string id)                
{
      var returnData = data;
      string callback = ControllerContext.Request.GetQueryNameValuePairs().Where(kv => kv.Key == "callback").Single().Value;    
      return Request.CreateResponse(HttpStatusCode.OK, returnData, new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter(),callback), new MediaTypeHeaderValue("text/javascript"));
}

where I am using this formatter. But the response is not containing the callback function's name wrapped around the JSON. It produces sth like:

({.....});

instead of:

myCallback({....});

Please suggest for a solution.


Solution

  • Used this to have control over which apis to allow CORS or not. Epic!