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.

    <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" />

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)

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");


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">
        url: 'https://code-sample.com/services/api/userdetailsservice',
        type: 'POST',
        data: JSON.stringify({ value: 'details-here' }),
        async: false,
        contentType: 'application/json',
        success: function (response
        error: function (response, Status, error) {



Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions