Got 400 error for pre-flight options CORS token request from OWIN-based WebAPI

元气小坏坏 提交于 2019-12-06 07:43:21

问题


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.



来源:https://stackoverflow.com/questions/30826706/got-400-error-for-pre-flight-options-cors-token-request-from-owin-based-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!