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

Posted

技术标签:

【中文标题】.net core 3.1 c# cors 不适用于 Angular 7【英文标题】:.net core 3.1 c# cors not working with angular 7 【发布时间】:2020-05-05 01:24:48 【问题描述】:

您好,我尝试了不同的方法来启用 cors,但我的代码失败了http://localhost:5000/Values 的资源。 (原因:CORS 标头“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] 是因为授权中间件还是要在端点上做些什么?

【问题讨论】:

【参考方案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");

【讨论】:

本地有什么用? IE。我会使用“example.com”作为与AllowCredentials 配对的原点,但是当我在我的开发机器上运行时,我该如何使用AllowAnyOrigin【参考方案2】:

在您的 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()之前

【讨论】:

【参考方案3】:

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

        //app.UseHttpsRedirection();           

        app.UseRouting();


        // global cors policy
        app.UseCors();


        app.UseAuthorization();

【讨论】:

【参考方案4】:

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

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

【讨论】:

以上是关于.net core 3.1 c# cors 不适用于 Angular 7的主要内容,如果未能解决你的问题,请参考以下文章

在 webapi .net core 3.1 上添加 app.useauthentication 时 Cors 失败

无法在.net core 3.1 web api中找出CORS

如何在 asp.net core 3.1 中为每种类型的请求启用 Cors

.NET Core 3.1 + Angular 上的 PreflightMissingAllowOriginHeader CORS 错误

适用于任何平台的 WPF .net Core 3.1 应用程序部署工具?

在 ASP.NET Core 3.1 中处理多环境的 CORS 策略