title: Geting error while posting data to different domain
body: <p>I am developing a website in which I need to post data to create a record.My server side code is on different domain. I need to call the method from that domain. My ajax code to call that method is as- </p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;        
  &lt;head runat="server"&gt;
      &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt; 
  
  &lt;script type="text/javascript"&gt;
      $(document).ready(function () {
              $('#create').click(function (e) {    
                  var url = 'http://abc.in/api/api/Patient/Create';
                  $.ajax({
                      url: url,
                      crossDomain: true,
                      contentType: "application/json",
                      dataType: "json",                         
                      data: JSON.stringify(getData()),
                      type: 'POST',                    
                      success: function (result) {                       
                      },
                      error: function (result) {
                      }
                  });
              });
       });    
      &lt;/script&gt;
  &lt;/head&gt;
  </code></pre>
  
  <p>and my server side code in Global.asax is-</p>
  
  <pre><code> public class MvcApplication : System.Web.HttpApplication
      {
          public static void RegisterRoutes(RouteCollection routes)
          {
              routes.MapHttpRoute(
              name: "Create",
              routeTemplate: "api/Patient/Create",
              defaults: new { controller = "Patient", action = "Create" }
          );
  
              routes.MapHttpRoute(
              name: "Update",
              routeTemplate: "api/Patient/Update",
              defaults: new { controller = "Patient", action = "Update" }
          );    
              routes.MapHttpRoute(
              name: "Get",
              routeTemplate: "api/Patient/Get/{id}",
              defaults: new { controller = "Patient", action = "Get" }
          );
  
             routes.MapHttpRoute(
             name: "GetUploadDocumentListByPatient",
             routeTemplate: "api/UploadFile/GetUploadDocumentListByPatient/{id}",
             defaults: new { controller = "UploadFile", action = "GetUploadDocumentListByPatient" }
         );    
              routes.MapHttpRoute(
                  name: "DefaultApi",
                  routeTemplate: "api/{controller}/{action}/{id}",
                  defaults: new {controller="Patient", action = "GetTest", id = RouteParameter.Optional }
              );
          }
  
          protected void Application_Start()
          {
              AreaRegistration.RegisterAllAreas();
              RegisterRoutes(RouteTable.Routes);
              GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
              GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());    
              var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
              json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;
          }
  </code></pre>
  
  <p>My CorsHandler is as follow-</p>
  
  <pre><code>public class CorsHandler : DelegatingHandler
      {
          private const string Origin = "Origin";    
          private const string AccessControlRequestMethod = "Access-Control-Request-Method";    
          private const string AccessControlRequestHeaders = "Access-Control-Request-Headers";    
          private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";    
          private const string AccessControlAllowMethods = "Access-Control-Allow-Methods";    
          private const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";   
  
          protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request,
              CancellationToken cancellationToken)
          {
              bool isCorsRequest = request.Headers.Contains(Origin);    
              bool isPreflightRequest = request.Method == HttpMethod.Options;    
              if (isCorsRequest)
              {
                  if (isPreflightRequest)
                  {
                      var 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);
                      }    
                      try
                      {
                          IEnumerable&lt;string&gt; headers = request.Headers.GetValues(AccessControlRequestHeaders);
                          ;    
                          if (headers != null)
                          {
                              string requestedHeaders = string.Join(", ",                                    request.Headers.GetValues(AccessControlRequestHeaders));    
                              if (!string.IsNullOrEmpty(requestedHeaders))
                              {                                    response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
                              }
                          }       
                          var tcs = new TaskCompletionSource&lt;HttpResponseMessage&gt;();    
                          tcs.SetResult(response);    
                          return tcs.Task;
                      }
                      catch
                      {
                          var tcs = new TaskCompletionSource&lt;HttpResponseMessage&gt;();    
                          tcs.SetResult(response);    
                          return tcs.Task;
                      }
                  }    
                  return base.SendAsync(request, cancellationToken).ContinueWith(t =&gt;
                  {
                      HttpResponseMessage resp = t.Result;
  
                      resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());    
                      return resp;
                  });
              }    
              return base.SendAsync(request, cancellationToken);
          }
      }
  </code></pre>
  
  <p>There is no issue while getting the record from different domain i.e. <code>abc.in</code>  by using ajax,it responds back with data.But when I try to post the data using above ajax call it gives </p>
  
  <pre><code>XMLHttpRequest cannot load http://abc.in/api/api/Patient/Create. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:56139' is therefore not allowed access. 
  </code></pre>
  
  <p>Am I missing something? By using Advanced rest client application provided by google, record is created successfully. Is my ajax call missing something?</p>