Wednesday, July 30, 2014

JSON-P with ASP.NET webapi

Way way back, I’ve written a post on JSONP with azure. This post would be an extension of it, though a little different. In this post we will see on how we can wrap up the JSON output from the WEB API in a wrapper, often called as padding. You can create your own custom wrapper to do this. We in this post however, keeping the things simple, would rather use nuget to extract a package for us, that would do the same.

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.

image

Right click on project reference in project explorer and choose manage nuget packages.

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

image

If you build the project you will get two errors:

image

Well, need not to worry, these error just showing you are on the right track. To resolve these double click on anyone of them and you would navigated to the class XmlDocumentationProvider. If you look closely, though the class implements the interface IDocumentationProvider, it is not implementing it fully. You just have to fix that. Implement that interface by hovering your mouse over it and clicking that blue line at the beginning.

image

After successfully implementing the Interface. Your project would build without errors. 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:             };
  11:  
  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, application_start method write the following lines of code to get yourself a JSONP formatter in action.


   1: protected void Application_Start()
   2: {
   3:     AreaRegistration.RegisterAllAreas();
   4:  
   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);
  11: }


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

Calling JSONP from Javascript is pretty simple like 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: });
   9:  
  10: function returnCallback(args) {
  11:     alert(args);
  12: }

Here, returnCallback is the method that would be called when the api would return the data back.

Share this post

0 comments

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

 
© 2013 Neelesh Vishwakarma
Posts RSS Comments RSS
Back to top