Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebAPI 2 - CORS not working with contentType application/json

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?

like image 225
Alex Avatar asked Feb 15 '23 20:02

Alex


1 Answers

You can either add an Options method to your controller which always just returns without error, or add the

[HttpOptions]
[AcceptVerbs("POST", "OPTIONS")]

attributes to the PostXXX Method of your controller.

like image 186
Alan McBee Avatar answered Feb 17 '23 10:02

Alan McBee