【发布时间】:2020-01-17 19:24:09
【问题描述】:
我的 WebAPI web.config 中有以下标头:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="https://localhost:44379" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Headers" value="X-Requested-With, content-type, Accept, Origin, Authorization, User-Agent, Referer" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
当我在前端发送以下 POST 调用时,出现错误:
"CORS 策略阻止了从源 'https://server-name/Grouping/api/Grouping/GetGroupByProcessId' 获取 'https://server-name/Grouping/api/Grouping/GetGroupByProcessId' 的访问权限:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。 "
和
选项https://server-name/Grouping/api/Grouping/GetGroupByProcessId401(未经授权)
var headers = new Headers();
headers.append("Content-Type", "application/json");
headers.append("Accept", "application/json");
fetch("https://<host-name>/Grouping/api/Grouping/GetGroupByProcessId", {
method: "POST",
credentials: "include",
headers: headers,
body: JSON.stringify({ GroupingValue: groupingValue }) //groupingValue is just a JSON array
})
.then(res => res.json())
.then(data => console.log(data))
检查控制台中的响应和请求标头,我看到以下内容,一切看起来都很好。
我似乎无法弄清楚为什么我不断收到未经授权的消息。
我的 GET 请求进行得很好。
This answer 建议您可以在帖子中发送 JSON,但我有 Allow-Headers 的标头,但它仍然无法正常工作。任何帮助,将不胜感激!
【问题讨论】:
-
在您的
WebApiConfig.cs文件中,在Register方法下,添加以下内容:EnableCorsAttribute cors = new EnableCorsAttribute("http://localhost:44379", "*", "GET,POST"); config.EnableCors(cors);
标签: c# asp.net-web-api