Got 400 error for pre-flight options CORS token re

2019-05-13 22:51发布

问题:

It is really strange.

I tried to make a CORS request to WebAPI2 (OWIN-based) to gain authentication token.

It always fails every other times. like 1st request fails, but 2nd request will go through. And the 3rd fails, but the 4th will go through.

I don't understand why it was working half of the times.

I check the browser request (chrome).

The one got failed always goes by OPTIONS method. The one went through always goes by POST.

But I always use post method with headers 'Content-Type': 'application/x-www-form-urlencoded'

So I guess the question is why sometime Chrome/fire fox send preflight request but sometime it doesn't.

BTW, it works totally fine in IE.

回答1:

You are correct that both Chrome and FireFox use the preflight OPTIONS request. So, prior to executing a POST, Chrome/FireFox sends the request with the OPTIONS verb. If it does not receive a response back from the server that tells the browser that it is allowed to send the cross domain request, then you'll get an error and the subsequent POST will not post.

You have to enable OPTIONS in your web.config (or using one of the approaches listed in this article): http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

For web.config try:

<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS,PUT"/>
        <add name="Access-Control-Allow-Headers" value="Content-Type, Accept"/>            
      </customHeaders>

IE has been slow in adopting the CORS standards, so that's why IE is working fine without OPTIONS enabled.