Web API With AJAX: Perform Cross-Domain AJAX Request Using POST Verb

In this article we will understand how to make Cross-Domain requests (Web API) using the ajax() function.

This is the "Web API with Ajax" article series. We have been talking about the Web API and various concepts of the ajax() function in this series. You can go through our previous articles here.

following links:

In this article we will understand how to make Cross-Domain requests (Web API)  using the ajax() function. So, let's create two projects, one for the client and the other for the service application of the Web API.  Here is the implementation of the client code.
 
Implement client application

Here is the implementation of the client part, we have used the ajax() function with the crossDomain propery "true" and we are sending a "person" object as data of the ajax() function.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="callAJAX.aspx.cs" Inherits="clientProject.callAJAX" %>

 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <script src="JQuery.js" type="text/javascript"></script>

    <script>

               $(document).ready(function () {

    $("#Save").click(function () {

        var person = new Object();

        person.name = "Sourav";

        person.surname = "Kayal";

        $.ajax({

            url: 'http://localhost:3413/api/person',

            type: 'POST',

            dataType: 'json',

            crossDomain: true,

            data: person,

            success: function (data, textStatus, xhr) {

                console.log('Cross domain POST data' + data);

            },

            error: function (xhr, textStatus, errorThrown) {

                console.log(errorThrown);

            }

        });

    });

});

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <input type="button" id="Save" value="Save Data" />

    </form>

</body>

</html>


So, we have implemented the client part. Now we will implement the server part in a separate Web API project. Here is the implementation of the Web API.
 

using System;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Net.Http.Formatting;

using System.Web.Http;

 

namespace WebApplication1.WebAPI

{

    public class person

    {

        public string name { get; set; }

        public string surname { get; set; }

    }

 

    public class personController : ApiController

    {

        [HttpPost]

        public string Post(person person)

        {

            return person.name + " " + person.surname;

        }

    }

}

The structure of the API is very simple. The Posr() action takes one argument of the person class that we will supply from the client end.

So, we have done the implementation of the Web API. Now we need to configure a Cross-Domain setup in the same application. So use one C# .cs file (class file) and add the following code to it. This code does nothing more than allow the Cross-Domain request using various HTTP verbs.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Threading;

using System.Threading.Tasks;

using System.Web;

 

namespace WebApplication1

{

    public class CorsHandler : DelegatingHandler

    {

        const string Origin = "Origin";

        const string AccessControlRequestMethod = "Access-Control-Request-Method";

        const string AccessControlRequestHeaders = "Access-Control-Request-Headers";

        const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";

        const string AccessControlAllowMethods = "Access-Control-Allow-Methods";

        const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";

 

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)

        {

            bool isCorsRequest = request.Headers.Contains(Origin);

            bool isPreflightRequest = request.Method == HttpMethod.Options;

            if (isCorsRequest)

            {

                if (isPreflightRequest)

                {

                    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

                    response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());

 

                    string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();

                    if (accessControlRequestMethod != null)

                    {

                        response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);

                    }

 

                    string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));

                    if (!string.IsNullOrEmpty(requestedHeaders))

                    {

                        response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);

                    }

 

                    TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();

                    tcs.SetResult(response);

                    return tcs.Task;

                }

                else

                {

                    return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>

                    {

                        HttpResponseMessage resp = t.Result;

                        resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());

                        return resp;

                    });

                }

            }

            else

            {

                return base.SendAsync(request, cancellationToken);

            }

        }

    }

}
 
Now we need to register a Cross-Domain handler in our application. So open the Global.asax file and put the following lines for the Application_Start() event.
 

GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());

The configuration is now finished and we are allowed to run the application. We are halting the application within the Post() method of the Web API and we are seeing that the data has come in the Post() method.
Post method of Web-API
Then the success method will execute within the ajax() method and here is the log of the browser's console:

success method
Conclusion

In this article we have learned how to make a Cross-Domain POST request. Hope you have understood it and are very much interested in implementing it in your next application.