JSON-P With ASP.Net Webapi

Way, way back, I wrote an article on JSONP with Azure. This article will be an extension of it, though a little different. In this article we will see how to wrap up the JSON output from the WEB API in a wrapper, often called padding. You can create your own custom wrapper to do this. In this article however, to keep things simple, we would rather use Nuget to extract a package for us, that would do the same thing.

Hit up Visual Studio and Load the new WEB API project from the template. Once that is done, we are good to go. Let's first get our wrapper from Nuget.


Right-click on the project references in the Solution Explorer and choose Manage Nuget Packages.

In the package manager, search for the WebApiContrib.Formatting.Jsonp package and choose Install.

package manager

If you build the project you will get the following two errors:


Well, there is no need to worry, these errors are just showing you are on the right track. To resolve these double-click on any one of them and you will be navigated to the class XmlDocumentationProvider. If you look closely, though the class implements the interface IDocumentationProvider, it is not implementing it fully. You just need to fix that. Implement that interface by hovering your mouse over it and clicking that Blue line at the beginning.

After successfully implementing the Interface, your project would build without errors. The next step is to add the class FormatterConfig in the App_start folder. The class would have the following code:

  1. public class FormatterConfig  
  2. {  
  3.      public static void RegisterFormatters  
  4.                      (MediaTypeFormatterCollection formatters)  
  5.      {  
  6.          var jsonFormatter = formatters.JsonFormatter;  
  7.          jsonFormatter.SerializerSettings = new JsonSerializerSettings  
  8.          {  
  9.              ContractResolver = new CamelCasePropertyNamesContractResolver()  
  10.          };  
  12.          var jsonpFormatter =   
  13.                  new JsonpMediaTypeFormatter(formatters.JsonFormatter);  
  14.          formatters.Insert(0, jsonpFormatter);  
  15.      }  
  16.  } 

Now we need to route the data going in/out from the webapi. Adding the following route in WebApiConfig.cs will do that.

  1. config.Routes.MapHttpRoute(  
  2.    name: "DefaultApi",  
  3.    routeTemplate: "api/{controller}/{id}/{format}",  
  4.    defaults: new { id = RouteParameter.Optional,  
  5.                      format = RouteParameter.Optional }  
  6. ); 

Finally, we need to register our new formatter, so in Global.asax.cs, the Application_start method writes the following lines of code to get yourself a JSONP formatter in action.

  1. protected void Application_Start()  
  2. {  
  3.     AreaRegistration.RegisterAllAreas();  
  5.     WebApiConfig.Register(GlobalConfiguration.Configuration);  
  6.     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  7.     RouteConfig.RegisterRoutes(RouteTable.Routes);  
  8.     BundleConfig.RegisterBundles(BundleTable.Bundles);  
  9.     FormatterConfig.RegisterFormatters  
  10.                 (GlobalConfiguration.Configuration.Formatters);  

Well, this is how to format your JSON to JSONP.

Calling JSONP from JavaScript is pretty simple, like a normal ajax call. In this case however one should provide the Callback function.

  1. $.ajax({  
  2.            type: 'GET',  
  3.               url: "http://localhost/api/values/GetUserName/1",  
  4.               callback: 'returnCallBack',  
  5.               contentType: "application/json",  
  6.               dataType: 'jsonp'  
  7.               })  
  8. });  
  10. function returnCallback(args) {  
  11.     alert(args);  

Here, returnCallback is the method that will be called when the API returns the data back.

Similar Articles