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.
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:
- public class FormatterConfig
- {
- public static void RegisterFormatters
- (MediaTypeFormatterCollection formatters)
- {
- var jsonFormatter = formatters.JsonFormatter;
- jsonFormatter.SerializerSettings = new JsonSerializerSettings
- {
- ContractResolver = new CamelCasePropertyNamesContractResolver()
- };
-
- var jsonpFormatter =
- new JsonpMediaTypeFormatter(formatters.JsonFormatter);
- formatters.Insert(0, jsonpFormatter);
- }
- }
Now we need to route the data going in/out from the webapi. Adding the following route in WebApiConfig.cs will do that.
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}/{format}",
- defaults: new { id = RouteParameter.Optional,
- format = RouteParameter.Optional }
- );
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.
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
-
- WebApiConfig.Register(GlobalConfiguration.Configuration);
- FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- BundleConfig.RegisterBundles(BundleTable.Bundles);
- FormatterConfig.RegisterFormatters
- (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.
- $.ajax({
- type: 'GET',
- url: "http://localhost/api/values/GetUserName/1",
- callback: 'returnCallBack',
- contentType: "application/json",
- dataType: 'jsonp'
- })
- });
-
- function returnCallback(args) {
- alert(args);
- }
Here, returnCallback is the method that will be called when the API returns the data back.