CORS asp.net核心WebAPI-缺少Access-Control-Allow-Origin标头

时间:2019-05-16 08:43:57

标签: c# asp.net-core cors

我有启用了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 上,而我调用的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

3 个答案:

答案 0 :(得分:2)

如果您有这种情况可能会发生

app.UseHttpsRedirection();

Startup.Configure 中,并且您的开发 https 证书不受浏览器信任。 http 端点上的调用将重定向到 https,然后该调用将失败并返回一个错误,抱怨 CORS 标头。

调试非常令人沮丧。错过了一个早上。

答案 1 :(得分:0)

这可能是由于服务器端错误而导致的,在这种情况下,将清除响应标头,同时也清除CORS响应标头。尝试启用异常并调试应用程序以查找错误。

另请参阅:asp net core - No 'Access-Control-Allow-Origin' header is present on the requested resource

答案 2 :(得分:0)

您可以尝试这个吗,

  services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder
                    .AllowAnyMethod()
                    .AllowCredentials()
                    .SetIsOriginAllowed((host) => true)
                    .AllowAnyHeader());
        });

并使用它

app.UseCors("CorsPolicy");

此代码适用于任何来源。我只是有类似的东西,当我直接在app.UseCors()中使用cors时,我遇到了问题,然后我尝试了一下并奏效了。 ps在app.UseMvc()之后不要使用app.UseCors()