【发布时间】:2023-03-09 02:42:01
【问题描述】:
我有一个关于在 ASP.NET Web API 中实现 cors 的问题。 我转向 SO 的原因是我尝试到处搜索,找到了很多教程和答案,但这些似乎都不适合我。
设置:
- 在 XAMPP 上运行的 Web 应用程序(HTML5、JS)(192.168.1.101:8080)
- 在 IIS Express 上运行的 API (ASP.net)(与 VS2013 集成)(192.168.1.101:52126)
Web 应用程序对 API 进行 ajax 调用,如下面的代码块所示。
$.ajax({
data: JSON.stringify(data),
type: 'POST',
url: 'http://localhost:52126/api/controller/action',
dataType: 'json',
contentType: 'application/json',
processData: false,
headers:
{
"Authorization": "Basic Base64Encrpytion"
},
success: function(data)
{
// Handle success
},
error: function(data)
{
// Handle error
}
});
这一切都在 localhost 中完美运行,包括 OPTION 预检。但是,当我从同一本地网络中的其他设备启动 Web 应用程序时,预检失败,当然,如果预检失败,其余调用也会被取消。
错误:
当尝试使用 Web 应用程序从同一网络中的另一台设备 (192.168.1.100) 查询 API 时,会生成以下响应:
控制台
OPTIONS http://192.168.1.101:52126/api/controller/action 400 (Bad Request)
OPTIONS http://192.168.1.101:52126/api/controller/action No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.101:8080/' is therefore not allowed access.
XMLHttpRequest cannot load http://192.168.1.101:52126/api/controller/action. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.101:8080/' is therefore not allowed access.
响应标头
Connection: close
Content-Length: 334
Content-Type: text/html; charset=us-ascii
Date: Wed, 05 Mar 2014 09:29:46 GMT
Server: Microsoft-HTTPAPI/2.0
在 localhost 上测试 Web 应用程序和 API 时,响应标头确实包含 Access-Control-Allow-Origin "*" 标头。
我尝试过的解决方案:
将以下代码添加到需要从域外访问的每个类中。
[EnableCors(origins: "*", headers: "*", methods: "*")]
将以下代码添加到 Web.config 文件中。
<httpprotocol>
<customheaders>
<add name="Access-Control-Allow-Origin" value="*"></add>
</customheaders>
</httpprotocol>
将以下代码添加到 WebApiConfig 文件中。
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
将以下代码添加到 applicationhost.config
<binding protocol="http" bindingInformation="192.168.1.101:52126:*" />
以下设置设为true
jQuery.support.cors = true
我也尝试过覆盖预检处理程序,但这似乎也失败了。
【问题讨论】:
-
请记住,Chrome 不允许您运行该示例,因为您在 url 上有
localhost。例如使用 Firefox 或将绑定更改为您的机器名称。 -
感谢您的回复。我已将 localhost 更改为机器本身的 ip,当我这样做时会弹出错误。使用 localhost 时,一切似乎都正常。此外,我正在尝试从网络中的其他设备访问 API。
-
要在您的网络中公开 API 而无需部署到 IIS,请read my answer 回答一个老问题
标签: javascript jquery asp.net asp.net-web-api cors