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


Sathish Nadarajan
SharePoint MVP
Published On :   06 Jul 2015
Visit Count
Today :  3    Total :   14906
Plan, Migrate, Secure, Report
SharePoint & Office 365 Tool. Simple & Easy to Use. 15-Day Trial!

SharePoint Office 365 Tool
Simple & Powerful Tool for Migration, Security & Reporting. Free Trial


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.

clip_image002

2. The console will be opened. On that type

Install-Package WebApiContrib.Formatting.Jsonp

3. We will get the success message as below.

clip_image004

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
             try
             {
                 writer = new StreamWriter(stream);
                 writer.Write(JsonpCallbackFunction + "(");
                 writer.Flush();
             }
             catch (Exception ex)
             {
                 try
                 {
                     if (writer != null)
                         writer.Dispose();
                 }
                 catch { }
 
                 var tcs = new TaskCompletionSource<object>();
                 tcs.SetException(ex);
                 return tcs.Task;
             }
 
             return base.WriteToStreamAsync(type, value, stream, content, transportContext)
                        .ContinueWith(innerTask =>
                        {
                            if (innerTask.Status == TaskStatus.RanToCompletion)
                            {
                                writer.Write(")");
                                writer.Flush();
                            }
 
                        }, TaskContinuationOptions.ExecuteSynchronously)
                         .ContinueWith(innerTask =>
                         {
                             writer.Dispose();
                             return innerTask;
 
                         }, TaskContinuationOptions.ExecuteSynchronously)
                         .Unwrap();
         }
 
         /// <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.

 [HttpGet]
         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.

 try{
 			 $.getJSON("http://localhost:38447/api/demo/MyAction/test?callback=?",
              function (Data) {
               alert(Data);
              })
              .fail(
              function (jqXHR, textStatus, err) {
              alert('Fail ' + err);
              });
 			 }catch(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.

SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Categories

Protect Your SharePoint