【问题标题】:CORS issue while migrating form .net core 2.2 to .net core 3.0 [duplicate]从.net core 2.2迁移到.net core 3.0时出现CORS问题[重复]
【发布时间】:2020-02-07 16:54:18
【问题描述】:

我在从 .net core 2.2 迁移到 .net core 3.0 时遇到了 cors 问题

  public void Configure(IApplicationBuilder app, IHostEnvironment env, Microsoft.AspNetCore.Hosting.IApplicationLifetime applicationLifetime)
        {
            NLog.LogManager.Configuration = new NLogLoggingConfiguration(Configuration.GetSection("NLog"));
            LogManager.Configuration.Variables["connectionString"] = Encryptor.GetNLogDB();
            LogManager.Configuration.Variables["ApplicationName"] = env.ApplicationName;
            LogManager.Configuration.Variables["EnvironmentType"] = env.EnvironmentName;
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCors("AllowAll");

            applicationLifetime.ApplicationStopping.Register(OnShutdown);
            applicationLifetime.ApplicationStarted.Register(OnStarted);

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseLogAndExceptionHandler();

            //app.UseCors();
            //app.UseSignalR(routes =>
            //{
            //    routes.MapHub<ApplicationHub>(SignalRHub);
            //    routes.MapHub<QuillHub>(QuillHub);
            //});
            app.UseEndpoints(endpoints => {
                endpoints.MapControllers();
            });
            //app.UseMvc();

            Initialize(app);
        }

public void ConfigureServices(IServiceCollection services)
        {
services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                    builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
            });
}

运行此程序时,我收到一条错误消息,说我不能同时使用 AllowAnyOrigin 和 AllowCredentials,当我删除其中任何一个时,我得到运行时错误已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*”。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

我想允许所有来源。

【问题讨论】:

    标签: asp.net-core


    【解决方案1】:

    基于CORS doc,AllowAnyOrigin 和 AllowCredentials 不能一起使用。

    尝试使用SetIsOriginAllowed 作为解决方法

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-26
      • 1970-01-01
      • 2020-05-28
      • 2019-06-14
      相关资源
      最近更新 更多