title: mvc webapi cross domain post
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/12732147/cors-with-webapi-for-xmlhttprequest">CORS with WebAPI for XmlHttpRequest</a>  </p>
  </blockquote>
  
  
  
  <p><br /> <br />
   I'm trying to implement cross-domain ajax post to my webApi project. I had few troubles with that: <br />
   1. I always was getting 204 error until changed my webapi action from 
  </p>
  
  <pre><code>public void submit(Submission model)
  </code></pre>
  
  <p>to
  </p>
  
  <pre><code>public bool submit(Submission model)
  </code></pre>
  
  <p>don't know why, but now I'm getting <code>200 OK</code> status <br /> <br />
   2. Still my ajax firing error callback. <br /> <br />
   3. Long time ago I solved this kind of error of cross-domain posting by adding
  </p>
  
  <pre><code>HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
  </code></pre>
  
  <p>to my controller. But now in webApi i'm inherent from <code>: ApiController </code> and this trick doesn't work. Shows me compiler <code>Error an object reference is required for the non-static field, method, or property"System.Web.HttpContext.Response.get"</code> <br /> <br />
   I have tryed to post via <code>dataType: 'JSONP'</code> but I get null model. <br /> <br />
   Here goes Javascript request:</p>
  
  <pre>
  var model = {
          "type": $("#model-type").val(),
          "subject": $("#subject-text").val(),
          "body": $("#body-text").val()
      };
  
      $.ajax({
          type: "POST",
          dataType: 'JSONP',
          url: $("#submit-url").val(),
          data: model,
          success: function () {
              alert("Succesfully submitted");
          },
          error: function () {
              alert("Error...");
          }
      });
  
  </pre>
  
  <p>What I'm doing wrong?</p>
  
  <h2>SOLVED</h2>
  
  <p>Thanks to everybody for helping me out. I found solution in one of the comment links. I used following approach, which I find pretty simple. <br />  <br />
  Source:<br />
  <a href="http://blogs.msdn.com/b/carlosfigueira/archive/2012/02/20/implementing-cors-support-in-asp-net-web-apis.aspx" rel="nofollow noreferrer">Implementing CORS support in ASP.NET Web APIs</a></p>
  
  <p><br />
  What I made: <br /> <br />
  1.  Created new Class in my project: <code>CorsHandler.cs</code> and just copy-pasted following code: <br /></p>
  
  <pre><code>
  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 SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
          {
              bool isCorsRequest = request.Headers.Contains(Origin);
              bool isPreflightRequest = request.Method == HttpMethod.Options;
              if (isCorsRequest)
              {
                  if (isPreflightRequest)
                  {
                      return Task.Factory.StartNew(() =>
                      {
                          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);
                          }
  
                          return response;
                      }, cancellationToken);
                  }
                  else
                  {
                      return base.SendAsync(request, cancellationToken).ContinueWith(t =>
                      {
                          HttpResponseMessage resp = t.Result;
                          resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
                          return resp;
                      });
                  }
              }
              else
              {
                  return base.SendAsync(request, cancellationToken);
              }
          }
      }
  
  </code></pre>
  
  <ol start="2">
  <li>Opened my <code>Global.asax</code> and modifyed  <code>Application_Start</code> :</li>
  </ol>
  
  <pre><code>
  protected void Application_Start()
          {
              AreaRegistration.RegisterAllAreas();
  
              RegisterGlobalFilters(GlobalFilters.Filters);
              RegisterRoutes(RouteTable.Routes);
  
              GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
          }
  
  </code></pre>
  
  <p>Pay attention to the last line in action. <br /> <br />
   This approach is compatible with MVC3 and .NET 4.0. Works great, now I can handle "success" and "error" callbacks in ajax.</p>