Cross Domain ASP.NET Web API GET & POST Data Using JQuery AJAX

When you have created a Restful API using the ASP.NET Web API and if your API is in one domain and the UI is in another domain then you might get errors due to cross-domain issues.

  1. http://localhost:5000/api/ 404 (Not Found).

  2. http://localhost:5000/api/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:54317' is therefore not allowed access. The response had HTTP status code 404.

In other words you cannot make a call to the WebAPI via your front end that is hosted on a different domain.

Then you can resolve it using  Web API Cross Handler, you need to add a WepAPICrossHandler.cs code in the App_Start folder and register this code in Application_Start().
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Net.Http;  
  6. using System.Threading;  
  7. using System.Threading.Tasks;  
  8. using System.Net;  
  9.   
  10. namespace WebAPI  
  11. {  
  12.     public class WepAPICrossHandler : DelegatingHandler  
  13.     {  
  14.         const string Origin = "Origin";  
  15.         const string AccessControlRequestMethod = "Access-Control-Request-Method";  
  16.         const string AccessControlRequestHeaders = "Access-Control-Request-Headers";  
  17.         const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";  
  18.         const string AccessControlAllowMethods = "Access-Control-Allow-Methods";  
  19.         const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";  
  20.   
  21.         protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)  
  22.         {  
  23.             bool isCorsRequest = request.Headers.Contains(Origin);  
  24.             bool isPreflightRequest = request.Method == HttpMethod.Options;  
  25.             if (isCorsRequest)  
  26.             {  
  27.                 if (isPreflightRequest)  
  28.                 {  
  29.                     HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);  
  30.                     response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());  
  31.   
  32.                     string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();  
  33.                     if (accessControlRequestMethod != null)  
  34.                     {  
  35.                         response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);  
  36.                     }  
  37.   
  38.                     string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));  
  39.                     if (!string.IsNullOrEmpty(requestedHeaders))  
  40.                     {  
  41.                         response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);  
  42.                     }  
  43.   
  44.                     TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();  
  45.                     tcs.SetResult(response);  
  46.                     return tcs.Task;  
  47.                 }  
  48.                 else  
  49.                 {  
  50.                     return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>  
  51.                     {  
  52.                         HttpResponseMessage resp = t.Result;  
  53.                         resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());  
  54.                         return resp;  
  55.                     });  
  56.                 }  
  57.             }  
  58.             else  
  59.             {  
  60.                 return base.SendAsync(request, cancellationToken);  
  61.             }  
  62.         }  
  63.     }  
  64. }  
For using this code you need to make the following change in the Application_Start() method in the Global.asax.cs file.
  1. GlobalConfiguration.Configuration.MessageHandlers.Add(new WepAPICrossHandler());  
After then we will add controller on our UI (front-end) side. Suppose we have added a HomeController.cs.
  1. public class HomeController : ApiController  
  2.     {  
  3.         public string GetEmployeeInformation(string JSONString)  
  4.         {  
  5.             var seriptSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();  
  6.             Employee employee = seriptSerialization.Deserialize<Employee>(JSONString);  
  7.             //if list then we can use like this  
  8.             //List<Employee> employee = seriptSerialization.Deserialize<List<Employee>>(JSONString);  
  9.             return employee.EmployeeName;  
  10.         }  
  11.   
  12.         public string PostSubmitdata([FromBody]Employee emp)  
  13.         {  
  14.             return emp.EmployeeName;  
  15.         }  
  16.     }  
 If you have found there is something error like : The type or namespace 'Script' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)
 
Then you have to add references for  System.Web.Extensions.dll
 
And the Employee class:
  1. public class Employee  
  2.     {  
  3.         public string EmployeeName { getset; }  
  4.         public EmployeeDetails empdetails { getset; }  
  5.     }  
  6.     public class EmployeeDetails  
  7.     {  
  8.         public string email { getset; }  
  9.         public string firstName { getset; }  
  10.         public string lastName { getset; }  
  11.     }  
Then we will look at the WebApiConfig.cs file in the App_Start folder.
  1. public static void Register(HttpConfiguration config)  
  2.        {  
  3.            config.Routes.MapHttpRoute(  
  4.                name: "DefaultApi",  
  5.                routeTemplate: "api/{controller}/{action}/{id}",  
  6.                defaults: new { id = RouteParameter.Optional }  
  7.            );  
  8.        }  
So we can write the GET and POST methods as shown below.
  1. <!DOCTYPE>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
  6.     <script language="javascript" type="text/javascript">  
  7.           
  8.         /**********************************Request****************************************/  
  9.         var reqdata = {  
  10.             EmployeeName: "JD Mishra",  
  11.             empdetails: {  
  12.                 email: '[email protected]',  
  13.                 firstName: 'Jagdev',  
  14.                 lastName: 'Mishra'  
  15.             }  
  16.         }  
  17.         var stringReqdata = JSON.stringify(reqdata);  
  18.   
  19.         /*************************************GET*****************************************/  
  20.         function GetEmployeeInformation() {  
  21.             var url = "http://localhost:5000/api/Home/GetEmployeeInformation?JSONString=" + stringReqdata;  
  22.             jQuery.ajax({  
  23.                 crossDomain: true,  
  24.                 dataType: "json",  
  25.                 url: url,  
  26.                 async: false,  
  27.                 context: document.body  
  28.             }).success(function (data) {  
  29.                 alert(data);  
  30.             });  
  31.         };  
  32.         /*************************************GET*****************************************/  
  33.         function PostSubmitdata() {  
  34.             var url = "http://localhost:5000/api/Home/PostSubmitdata";  
  35.             jQuery.ajax({  
  36.                 crossDomain: true,  
  37.                 async: false,  
  38.                 type: "POST",  
  39.                 url: url,  
  40.                 data: stringReqdata,  
  41.                 dataType: "json",  
  42.                 context: document.body,  
  43.                 contentType: 'application/json; charset=utf-8'  
  44.             }).success(function (data) {  
  45.                 alert(data);  
  46.             })  
  47.         }  
  48.     </script>  
  49. </head>  
  50. <body>  
  51.     <a href="#" onclick="GetEmployeeInformation();">Get</a><br />  
  52.     <a href="#" onclick="PostSubmitdata();">Post</a>  
  53. </body>  
  54. </html>  
 Thanks.