【问题标题】:Issue in CORS in ASP .NET Core - The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*ASP .NET Core 中的 CORS 问题 - 响应中的“Access-Control-Allow-Origin”标头的值不能是通配符 '*
【发布时间】:2020-08-30 11:22:03
【问题描述】:

我收到以下错误

从源 'http://localhost:23456' 访问 XMLHttpRequest 在 'http://localhost:5000/api/values/track/?name=name&time=1589425390870' 已被 CORS 策略阻止:响应中的 'Access-Control-Allow-Origin' 标头的值不能是通配符 '* ' 当请求的凭据模式为 'include' 时。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

我已经像下面这样配置了 Asp.net 核心应用程序

public void ConfigureServices(IServiceCollection services)
        {

            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader().AllowCredentials() ;
            }));


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors("MyPolicy");
            app.UseMvc();
        }

内容类型:application/x-www-form-urlencoded

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: c# asp.net-core asp.net-web-api cors


    【解决方案1】:

    当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*”。

    由于错误表明您使用 AllowAnyOriginAllowCredentials 方法配置您的应用程序,这导致 CORS 服务返回无效的 CORS 响应。

    您可以修改代码以启用特定来源,如下所示。

    builder.WithOrigins("set_specified_origins_here")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials();
    

    有关“设置允许的来源”的详细信息,请查看以下文档:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.0#set-the-allowed-origins-1

    【讨论】:

    • 韩飞,它对我有用。衷心感谢您 :) 感谢您的快速帮助。
    猜你喜欢
    • 2018-10-09
    • 2020-09-21
    • 2017-06-23
    • 2019-02-08
    • 2019-06-17
    • 2019-01-16
    • 1970-01-01
    • 2017-12-11
    • 2021-10-20
    相关资源
    最近更新 更多