来自基于OWIN的WebAPI的飞行前选项CORS令牌请求出现400错误 [英] Got 400 error for pre-flight options CORS token request from OWIN-based WebAPI

查看:198
本文介绍了来自基于OWIN的WebAPI的飞行前选项CORS令牌请求出现400错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真的很奇怪.

我试图向WebAPI2(基于OWIN)发出CORS请求以获取身份验证令牌.

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

它总是每隔两次失败.例如第一个请求失败,但第二个请求将通过.第3次失败,但第4次会通过.

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.

我检查了浏览器请求(chrome).

I check the browser request (chrome).

失败的人总是采用OPTIONS方法.经历过的总是通过POST.

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

但是我总是使用标题为"Content-Type"的post方法:"application/x-www-form-urlencoded"

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

所以我想问题是为什么Chrome/fire fox有时会发送预检请求,而有时却没有.

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

顺便说一句,它在IE中完全可以正常工作.

BTW, it works totally fine in IE.

推荐答案

您正确的认为Chrome和FireFox都使用预检OPTIONS请求.因此,在执行POST之前,Chrome/FireFox使用OPTIONS动词发送请求.如果它没有从服务器返回响应,告诉浏览器允许发送跨域请求,则您将收到错误消息,并且后续的POST将不会发布.

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.

您必须在web.config中启用OPTIONS(或使用本文列出的方法之一): http://www.asp .net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

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

对于web.config,请尝试:

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在采用CORS标准方面进展缓慢,因此这就是在未启用OPTIONS的情况下IE仍能正常工作的原因.

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

这篇关于来自基于OWIN的WebAPI的飞行前选项CORS令牌请求出现400错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆