WebAPI 2 - CORS not working with contentType appli

2019-06-24 03:21发布

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?

3条回答
唯我独甜
2楼-- · 2019-06-24 03:54

The only Content-type values that won’t trigger a CORS preflight request are text/plain, multipart/form-data, application/x-www-form-urlencoded.

查看更多
一纸荒年 Trace。
3楼-- · 2019-06-24 04:06

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.

查看更多
\"骚年 ilove
4楼-- · 2019-06-24 04:10

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.

查看更多
登录 后发表回答