title: Web API 2 Cors Request Error
body: <p>I am trying to get CORS set up for a project I am working on with WebAPI 2. I started having issues, so I created a demo app directly from asp.net forums <a href="http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api" rel="nofollow noreferrer">here</a>. Everything was working correctly until I needed to use json as the content type. Then I started getting:</p>
  
  <blockquote>
    <p>Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.</p>
  </blockquote>
  
  <p>I understand with this content type sends preflight requests, but I am dumbfounded how I can get this to pass. Am I missing something? As soon as I remove the "contentType: 'application/json'" attribute from AJAX request, it works. </p>
  
  <p>TestController.cs</p>
  
  <pre><code>[Authorize]
  [EnableCors(origins: "*", headers: "*", methods: "*")]
  public class TestController : ApiController
  {
      // GET api/&lt;controller&gt;
      public HttpResponseMessage Get()
      {
          return new HttpResponseMessage()
          {
              Content = new StringContent("GET: Test message")
          };
      }
  
      public HttpResponseMessage Post([FromBody]string name)
      {
          return new HttpResponseMessage()
          {
              Content = new StringContent("POST: Test message")
          };
      }
  
      public HttpResponseMessage Put()
      {
          return new HttpResponseMessage()
          {
              Content = new StringContent("PUT: Test message")
          };
      }
  }
  </code></pre>
  
  <p>WebApiConfig.cs</p>
  
  <pre><code>public static void Register(HttpConfiguration config)
      {
          // Web API configuration and services
          config.EnableCors();
  
          // Web API routes
          config.MapHttpAttributeRoutes();
  
          config.Routes.MapHttpRoute(
              name: "DefaultApi",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );
      }
  </code></pre>
  
  <p>Ajax Request</p>
  
  <pre><code>$.ajax({
              type: "POST",
              url: 'http://localhost:17515/',
              data: JSON.stringify("Test"),
              xhrFields: {
                  withCredentials: true
              },
              contentType: "application/json"
          });
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/LQM7o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LQM7o.png" alt="enter image description here"></a></p>
  
  <p><a href="https://i.stack.imgur.com/Ar99c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ar99c.png" alt="enter image description here"></a></p>