.net core 3.1 c# cors 不适用于 angular 7

.net core 3.1 c# cors not working with angular 7

你好,我尝试了不同的方法来启用 cors,但我的代码失败了 is.am 使用 spa 应用程序呈现数据但无法通过 cors.browser 显示错误 Cross-Origin 请求被阻止:同源策略不允许读取位于 http://localhost:5000/Values 的远程资源。 (原因:缺少 CORS header ‘Access-Control-Allow-Origin’)。

 public void ConfigureServices(IServiceCollection services)
    {
       services.AddControllers().AddNewtonsoftJson(opt =>
        {
            opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });
        services.AddCors();
        services.AddSignalR();
        services.AddControllersWithViews();
        services.AddDbContext<DataContext>(x =>
        {
            x.UseLazyLoadingProxies();
            x.UseMySql(Configuration.GetConnectionString("DefaultConnection"));
        });
        IdentityBuilder builder = services.AddIdentityCore<User>(opt =>
        {opt.User.RequireUniqueEmail = true;            
        }).AddRoles<IdentityRole>();
        builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
        builder.AddEntityFrameworkStores<DataContext>();
        builder.AddSignInManager<SignInManager<User>>();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                        .GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                    ValidateIssuer = false,
                    ValidateAudience = false

                };
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        if (string.IsNullOrEmpty(accessToken) == false)
                        {
                            context.Token = accessToken;
                        }
                        return Task.CompletedTask;
                    }
                };
            });
        services.AddAuthorization(options =>
        {
            options.AddPolicy(constant.RequireVisionTrackAdminRole, policy => policy.RequireRole(constant.VisionTrackAdmin));
            options.AddPolicy(constant.RequireAdminRole, policy => policy.RequireRole(constant.Admin, constant.VisionTrackAdmin));
        });
        services.AddScoped<IAuthRepository, AuthRepository>();
        services.AddAutoMapper(typeof(VisionTrackRepository).Assembly);
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/build";
        });
    }

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }       
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSpaStaticFiles();          
        app.UseRouting();
        app.UseCors(
            options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
        );
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<VisionTrackHub>("/VisionTrack").RequireCors("CorsPolicy");
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}").RequireCors("CorsPolicy");

        });
        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseReactDevelopmentServer(npmScript: "start");
            }
        });

    }

也尝试过此指南无效[https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1] 是因为授权中间件还是要在端点上做些什么?

我认为这与事实有关,you cannot use options.AllowAnyOrigin() 和身份验证中间件。在您的情况下,您有义务明确定义允许的来源。

如果您按照下面给出的方式定义了 CORS,则不应发生请求块。

services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
    builder
        .WithOrigins(new[]{"http://YOUR_FRONTEND_ORIGIN"})
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials();
}));
app.UseCors("CorsPolicy");

我解决了注释行 //app.UseHttpsRedirection();

        //app.UseHttpsRedirection();           

        app.UseRouting();


        // global cors policy
        app.UseCors();


        app.UseAuthorization();

在您的 Startup 文件中,您有两个主要方法,ConfigureServicesConfigure 方法。

在你的ConfigureServices方法中定义如下:

 services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());
        });

然后在 Configure 方法中添加这一行:

app.UseCors("CorsPolicy");

注:app.UseCors("CorsPolicy")应该在app.UseRouting()之后app.UserAuthentication()

之前

这个解决方案解决了我的问题:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddCors();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors(
            options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()
        );

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

https://github.com/dotnet/aspnetcore/issues/16672