【发布时间】:2019-10-03 11:41:24
【问题描述】:
我有启用 CORS 的 ASP.net WebApi Core。它是 Visual Studio ASP.net Core Web API 模板。添加的唯一代码是支持 CORS 的代码:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
/* other stuff */
app.UseCors(builder => builder
.WithOrigins("https://localhost:44310")
.AllowAnyMethod()
.AllowAnyHeader());
app.UseMvc();
}
}
我的 API 托管在 localhost:44361 和 mycalling WEB 上 localhost:44310。有不同的端口,所以我的请求来自不同的来源。这就是为什么应该有标题 Access-Control-Allow-Origin 作为响应。它丢失了,我在浏览器控制台中看到错误:
Access to fetch at 'https://localhost:44361/api/values'
from origin 'https://localhost:44310' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors'
to fetch the resource with CORS disabled.
问题出在哪里?
请求标头:
GET https://localhost:44361/api/values HTTP/1.1
Host: localhost:44361
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Origin: https://localhost:44310
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36
Accept: */*
Referer: https://localhost:44310/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
响应标头:
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/10.0
X-SourceFiles: =?UTF-8?B?RDpcRGV2ZWxvcG1lbnRcQyNfcHJvZ3JhbW1pbmdcU0FNUExFU1xDb3JzQXBpU2ltdWxhdG9yXENvcmVBcGlcYXBpXHZhbHVlcw==?=
X-Powered-By: ASP.NET
Date: Thu, 16 May 2019 08:37:54 GMT
【问题讨论】:
-
问题中的所有内容对我来说都不错。你能把它变成minimal reproducible example吗?
-
.AllowAnyOrigin()也会发生这种情况吗? -
是的,结果相同。
-
这是一个异常值,但会增加我最近的经验。就我而言,我添加了访问 API 资源的 MFA 要求。 API 抛出 401 但此错误清除了标头...因此不存在任何 Access-Control-Allow-Origin 标头。关键是在对 CORS 进行故障排除之前确保您的请求中没有错误
标签: c# asp.net-core cors