SharePoint Pals
 | Sign In
XMLHttpRequest cannot load http://Site/api/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://MyCallingSite’ is therefore not allowed access. SharePoint 2013 Error
by Sathish Nadarajan 6 Jul 2015
SharePoint MVP
Today  :   6     Total  :    11961

In the previous articles, Creating WebApi, and Calling WebApi, we saw how to create a WebAPI and how to call them from the Javascript.

But, not all the browsers accepts this type of calling. For me, it works like charm in Internet Explorer. But in Chrome, this method does not work. I faced with an exception like No ‘Access-Control-Allow-Origin’. This is something the browser restricts to call the API from different domain.

The purpose of creating an API itself comes under a question at this point. Here, either we can make the API to adopt the CORS rules. There are quite a lot of articles around this.

But in my scenario, instead of passing the JSON Object, we can pass back the JSONP and this is much simpler too.

To pass the JSONP object back, the below steps can be followed.

1. In the Visual Studio Open the Package Manager Console.


2. The console will be opened. On that type

Install-Package WebApiContrib.Formatting.Jsonp

3. We will get the success message as below.


4. Add a Class under “App_Start” as FormatterConfig.cs

 using Newtonsoft.Json;
 using Newtonsoft.Json.Converters;
 using Newtonsoft.Json.Serialization;
 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
 using System.Net;
 using System.Net.Http;
 using System.Net.Http.Formatting;
 using System.Net.Http.Headers;
 using System.Threading.Tasks;
 using System.Web;
 using WebApiContrib.Formatting.Jsonp;
 namespace MyFirstAPI
     public class JsonpFormatter : JsonMediaTypeFormatter
         public JsonpFormatter()
             SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
             SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));
             JsonpParameterName = "callback";
         /// <summary>
         ///  Name of the query string parameter to look for
         ///  the jsonp function name
         /// </summary>
         public string JsonpParameterName { get; set; }
         /// <summary>
         /// Captured name of the Jsonp function that the JSON call
         /// is wrapped in. Set in GetPerRequestFormatter Instance
         /// </summary>
         private string JsonpCallbackFunction;
         public override bool CanWriteType(Type type)
             return true;
         /// <summary>
         /// Override this method to capture the Request object
         /// </summary>
         /// <param name="type"></param>
         /// <param name="request"></param>
         /// <param name="mediaType"></param>
         /// <returns></returns>
         public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, System.Net.Http.HttpRequestMessage request, MediaTypeHeaderValue mediaType)
             var formatter = new JsonpFormatter()
                 JsonpCallbackFunction = GetJsonCallbackFunction(request)
             // this doesn't work unfortunately
             //formatter.SerializerSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
             // You have to reapply any JSON.NET default serializer Customizations here    
             formatter.SerializerSettings.Converters.Add(new StringEnumConverter());
             formatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
             return formatter;
         public override Task WriteToStreamAsync(Type type, object value,
                                         Stream stream,
                                         HttpContent content,
                                         TransportContext transportContext)
             if (string.IsNullOrEmpty(JsonpCallbackFunction))
                 return base.WriteToStreamAsync(type, value, stream, content, transportContext);
             StreamWriter writer = null;
             // write the pre-amble
                 writer = new StreamWriter(stream);
                 writer.Write(JsonpCallbackFunction + "(");
             catch (Exception ex)
                     if (writer != null)
                 catch { }
                 var tcs = new TaskCompletionSource<object>();
                 return tcs.Task;
             return base.WriteToStreamAsync(type, value, stream, content, transportContext)
                        .ContinueWith(innerTask =>
                            if (innerTask.Status == TaskStatus.RanToCompletion)
                        }, TaskContinuationOptions.ExecuteSynchronously)
                         .ContinueWith(innerTask =>
                             return innerTask;
                         }, TaskContinuationOptions.ExecuteSynchronously)
         /// <summary>
         /// Retrieves the Jsonp Callback function
         /// from the query string
         /// </summary>
         /// <returns></returns>
         private string GetJsonCallbackFunction(HttpRequestMessage request)
             if (request.Method != HttpMethod.Get)
                 return null;
             var query = HttpUtility.ParseQueryString(request.RequestUri.Query);
             var queryVal = query[this.JsonpParameterName];
             if (string.IsNullOrEmpty(queryVal))
                 return null;
             return queryVal;

5. The class, I have included in the Source code at the bottom of this post.

6. On the Global.asax.cs, under Application_start method, add this line.

 GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter()));

7. The Demo Controller class will be something like below.

         public string MyAction(string testParameter)
             //Do the Action Here
             return "My Test";

8. Now, execute this by clicking the F5.

9. From the Chrome, execute the below line of code.

              function (Data) {
              function (jqXHR, textStatus, err) {
              alert('Fail ' + err);

10. That’s it. Now, we will get the “My Test” string as a JSONP object. Now, we are good to process this.

11. This is a very simple way of communicating with our WebAPI from our SharePoint Client Object Code.

Happy Coding,

Sathish Nadarajan.

blog comments powered by Disqus

SharePoint Pals

SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile


Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community

SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to in a word document.

Related Resources

Recent Tweets

Twitter October 23, 22:21
How to Add/Remove User Custom Actions (in Site Actions Menu) Programmatically using CSOM PNP in SharePoint -

Twitter October 21, 21:34
How to Add a JS Link Reference to the Display Form or Any other ASPX Programmatically using CSOM PNP in SharePoint -

Twitter October 20, 13:01
How to Add a JS Link Reference to the NewForm and EditForm Programmatically using CSOM PNP in SharePoint Office 365-

Twitter October 12, 12:15
How to Deploy Provider Hosted Apps (Add-Ins) by App Stapling in SharePoint Office 365 -

Twitter October 11, 13:39
How to Deploy Provider HostedApp programmatically using CSOM in SharePoint Office 365 Activating Developer Feature -

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation