Ajax JSON cross domain call to REST service

Ajax JSON cross domain call to REST service

Hello everyone,

I'm going to share the code-sample for Ajax cross domain call to REST service with JSON Request.

Keeping in mind, if you working on to call cross domain to REST service. Here server handle two requests each operations. 

  1. First one for verify the request is OK and return to 200.
  2. Send one is revert back the response.

You will have to think about the security issues and be careful before doing something like 'Access-Control-Allow-Origin: *'


Always return the headers above, not just on OPTION requests. First needs it in the response from the POST.


Table of Contents

1. In the step 1, we added the custom headers in the config file.

2. In the step 2, execute the ajax request.

Step 1 :


In this step, need to add protocol section from web.config file.


  <httpProtocol>
   <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
   </customHeaders>
 </httpProtocol>

Some time the above code is not working that time we can trying to added following which are given below.


You can remove protocol section from web.config that we have added.



Add following method in Global.asax


protected void Application_BeginRequest(object sender, EventArgs e)
{
    CrossDomain_AjaxCallJSON();
}

private void CrossDomain_AjaxCallJSON()
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

     if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
     {
         HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
         HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
         HttpContext.Current.Response.End();
     }

}

Step 2


In this step, need to call the ajax request with cross domain request URL just like (https://code-sample.com/services/api/userdetailsservice).


<script type="text/javascript">
    $.ajax({
        url: 'https://code-sample.com/services/api/userdetailsservice',
        type: 'POST',
        data: JSON.stringify({ value: 'details-here' }),
        async: false,
        contentType: 'application/json',
        success: function (response
                    console.log(response
        },
        error: function (response, Status, error) {
            console.log(response);
            console.log(Status);
        }
    });


</script>


ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^