【发布时间】:2019-09-16 02:32:07
【问题描述】:
我有一个网站 1 和一个 Web API 2 我的 Web API 有一个方法名称
public string Index()
{
return "Hello world from site 2";
}
在控制器值中。 我像这样从网站 1 调用我的 API
$.ajax({
url: relativeUrl,
headers: { "Authorization": "Bearer " + accessToken },
type: "GET"
})
.done(function (result) {
console.log("Result: " + result);
alert(result);
})
.fail(function (result) {
console.log("Error: " + result.statusText);
alert(result.statusText);
});
但我的 js 控制台出现以下错误。
从源“网站 1”访问“Web API 2”的 XMLHttpRequest 已 被 CORS 策略阻止:请求标头字段授权不是 Access-Control-Allow-Headers 在预检响应中允许。
我在我的控制器中添加:
[EnableCors(origins: "*", headers: "*", methods: "*", exposedHeaders: "X-Custom-Header")]
在我的 WebAPIConfig.cs 中
config.EnableCors();
在我的 Web.config 中
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
但即使这样我仍然有错误,我不明白我需要添加什么以及在哪里。
【问题讨论】:
-
您是否在
localhost上同时运行网站和API?
标签: asp.net ajax asp.net-web-api cors