Wednesday, October 29, 2014

SharePoint 2013 Online and ASP.NET Web API using JSONP

Consider a scenario where you have to display data or make decisions on a SharePoint 2013 page based on the data that exists in a database. Here is what you can do:

Abstract:
1. Create an Empty ASP.NET Web API project.
2. Enable the project for JSONP format
3. Add the Controller, Model, the business and data access logic to the service
4. Deploy the Service
5. Add script to SharePoint 2013 page

Details:
1. Create an Empty ASP.NET Web API project.
This is fairly simple step, all you need is MVC4 or above and .NET Framework 4.5. Using Visual Studio 2012/2013, Add new project, select an empty project and check the Web API box and click OK.

2. Enable the project for JSONP format:
- Open package manager in visual studio (Tools>NuGet Package Manager > Package Manager Console and run the following command, it will add the required dlls to your project:

Install-Package WebApiContrib.Formatting.Jsonp

- In App_Start folder of the project, create a new class:

    public class FormatterConfig
    {
public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
        {
            var jsonFormatter = formatters.JsonFormatter;
            jsonFormatter.SerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            // Insert the JSONP formatter in front of the standard JSON formatter.

            var jsonpFormatter = new JsonpMediaTypeFormatter(formatters.JsonFormatter);
            formatters.Insert(0, jsonpFormatter);
        }

    }


The Application_Start method in your Global.asax.cs should look like this:

        protected void Application_Start()
        {
            FormatterConfig.RegisterFormatters(GlobalConfiguration.Configuration.Formatters);
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }

3. Add the Controller, Model, the business and data access logic to the service
I added the "Web API Controller Class (v2)" in the project.

4. Deploy the Service
- Create a new site in IIS, create bindings with a host-name and SSL.
NOTE: If you won't use SSL, you'll see the mixed content warnings or "security risk" warnings from browsers when you'll call the service from JavaScript. 
- Publish the service from visual studio and copy the published files to the site directory.

4. Test:
Create an HTML page and paste the following code in it. This code should work. (if it doesn't, open developer toolbar of the browser to make sure there are no errors).

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<button id="getJsonp">Get JSONP</button>
<script type="text/javascript">
$("#getJsonp").click(function () {
$.ajax({
        type: 'GET',
              url: "http://localhost/api/values/1",
              callback: callbackFunc,
              contentType: "application/json; charset=utf-8",
              dataType: 'jsonp'
              }).done(function(data){
alert(data);
});
});

function callbackFunc(resultData) {
}
</script>
</body>
</html>

5. Add script to SharePoint 2013 page
If it passes the above test, the highlighted (in blue) jQuery script can be added to the SharePoint page. Make sure you replace the localhost with an actual host-name accessible to all users, of course :)

No comments:

Post a Comment

Feel free to give constructive feedback or let me know if it was helpful.