CORS | Access-Control-Allow-Origin | MAKING JSONP REQUEST and MVC ACTION TO RETURN JSONP

(CROSS DOMAIN COMMUNICATION WITH JSONP using ASP.NET MVC)

IIS: Allow cross origin for a website 

Make below entry in respective web.config


  <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>

WHY JSONP?

Same-origin policy in your browser is the only reason, which blocks the script running in your window if origin is different. As per standard you can't have different origin for same window. Origin means protocol//host:port

Below sample URLs will be treated as different origin for the browser. We can resolve this by adding Access-Control-Allow-Origin: * or origin in response header. Find more implementing CORS for your site.

http://xyx.com 
http://abc.xyx.com
https://xyx.com  
http://xyx.com:1212 


What JSONP resolves ?

Since same-orgign policy is in place and want avoid CORS because of other reason, JSONP allows to load the script in browser using AJAX and once the response return for the request AJAX calls the callback method.

In addition to that, JSONP is an another approach that allows you to utilize set of data from other site to your site or you can push the data from back-end to your subscriber(browser who is making call). Back-end has option to check subscriber request and manipulate response according to request/client or based upon the query params. I think most people are utilizing this approach to communicate domain object to your browser and exposing data as service response. Alternative and recommended solution is CORS if it fits your need. 

Note: JSONP only supports the GET request.

WHAT TO DO IN CODE IF NEED TO HANDLE JSONP REQUEST IN MVC

For the article I have considered ASP.NET MVC to return JSONP


public ContentResult ApiResult(string callback)
{
   JsonObjectModel obj = new JsonObjectModel() { Name = "XYZ", Address = "ABC" };
   string objectString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
   return Content(String.Format("{0}({1});",callback,new JavaScriptSerializer().Serialize(obj)),"application/javascript");
}

HOW TO MAKE JSONP REQUEST

<script src="[path]/jquery-1.7.1.min.js" type="text/javascript"></script>     <script type="text/javascript"> 
        function jsonCallback(data) {
            alert('JSONP Data:' + data.Name + ','+data.Address);
        }
 
        (function ($) {
            $.ajax({
                jsonpCallback: 'jsonCallback',
                url: 'http://host/controller/apiresult?callback=?',
                dataType: 'jsonp',
                success: function(dataWeGotViaJsonp){
                     console.log('Response return from server:200-OK');
                },
                error: function (e) {
                    console.log(e.message);
                }
            });
 
        })(jQuery);
</script> 

Note: 

1. Ensure AJAX request has  dataType: 'jsonp'
2. Request type is GET


Comments

Popular posts from this blog

Difference between Parse/TryParse/ParseExact/TryParseExact

Benefits of Test Driven Development (TDD)

Version history of C#