从.NET Core 2.2迁移到.NET Core 3.0时发生CORS问题

从.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策略均阻止了运行时错误:对预检请求的响应未通过访问控制检查:当请求的凭据模式为“ include”时,响应中的“ Access-Control-Allow-Origin”标头不得为通配符“ *”。 XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。

我想允许所有起源。

评论
  • 占领网吧
    占领网吧 回复

    AllowAnyOrigin and AllowCredentials could not be used together based on CORS doc.

    Try to use SetIsOriginAllowed as a workaround

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