I've got an Asp.net WebApi 2 project, with a Booking
controller
If I try to post this from my client-side js:
$.ajax({
url: 'http://localhost:57517/api/booking',
type: 'POST',
crossDomain:true,
data: {AdultPaxCount:1},
contentType: "application/json"
});
I get a not-allowed error (and the Post
action on my BookingController
is not hit)
However;
If I remove the
contentType: "application/json"
section, it 'works' (it is sent to the controller)
Am I missing something in my setup?
The only Content-type values that won’t trigger a CORS preflight request are text/plain, multipart/form-data, application/x-www-form-urlencoded.
With that content-type, the browser will preflight the request. This means that the browser will send an OPTIONS request initially, and will only send the underlying request if your server responds appropriately to the preflight. So, the error is caused by your server rejecting the preflight (OPTIONS) request. You will either need to handle the preflight request server-side, or ensure the browser does not preflight the request by only sending a "simple" cross-origin request. More in the preflighting section of the MDN article on CORS.
You can either add an Options method to your controller which always just returns without error, or add the
attributes to the PostXXX Method of your controller.