首页 > 解决方案 > CORS 政策已被阻止我的子域

问题描述

我有一个相同的域,其中之一是没有前缀 www 的域。例如,

  1. https://www.example.com
  2. https://example.com

第一个域工作正常,因为它是默认域。但是当我执行 CRUD 或访问任何 api 服务时,第二个出现错误。

从源“ https://example.com ”访问“ https://www.example.com/hubCon/negotiate ”的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:当请求的凭据模式为“包含”时,响应中“Access-Control-Allow-Origin”标头的值不能是通配符“*”。XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

试了一下微软发布的文章中的代码,还是不行。

我正在使用 .Net Core 2.2 版本。这是我的 Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(MyAllowSpecificOrigins,
            builder =>
            {
                builder.WithOrigins("https://example.com")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowAnyOrigin()
                .AllowCredentials();
            });
        });

        services.AddMvc().AddJsonOptions(options =>
        {
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


        services.AddSignalR();
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseCors(MyAllowSpecificOrigins);
        app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
        });

        app.UseHttpsRedirection();
        app.UseStatusCodePages();
        app.UseStaticFiles();
        app.UseAuthentication();


        app.UseSignalR(routes =>
        {
            routes.MapHub<HubSignal>("/hubCon");
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}"
                );
        });
    }

所以,我不明白为什么该项目会出错。

感谢您的回答。

标签: asp.net-core.net-corecorsasp.net-core-webapi

解决方案


您不能将 AllowAnyOrigin 与 AllowCredentials 一起使用。下面是一个允许使用 CORS 的通配符域的示例。

此代码在 ConfigureServices 中:

services.AddCors(options =>
        {
            options.AddPolicy("_AllowOrigin",
                builder => builder
                    .SetIsOriginAllowedToAllowWildcardSubdomains()
                    .WithOrigins("https://localhost:44385", "https://*.azurewebsites.net", "http://*.azurewebsites.net")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                );
        });

不要忘记在控制器中装饰您的操作:

    [EnableCors("_AllowOrigin")]

推荐阅读