CORS 错误,无法从 asp.net 核心后端接收数据

CORS Error, can't receive data from asp.net core backend

我刚刚开始使用 Web 服务。我用 angular 前端创建了一个 asp.net 核心应用程序。

我已经将 CORS 添加到我的网络服务中 startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        //services.AddControllersWithViews();
        services.AddControllers();

        services.AddDbContext<BuchverwaltungDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        // In production, the Angular files will be served from this directory
        //services.AddSpaStaticFiles(configuration =>
        //{
        //    configuration.RootPath = "ClientApp/dist";
        //});
        services.AddCors();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseCors(options =>
        options.WithOrigins("http://localhost:4200/")
        .AllowAnyMethod()
        .AllowAnyHeader());

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            //Swagger hier einbauen
        }
        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();
        if (!env.IsDevelopment())
        {
            app.UseSpaStaticFiles();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");
        });

        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "ClientApp";

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

下面是我尝试在 angular 前端阅读书籍的方式:

getBooks() {
return this.http.get(this.baseURL + "/books")
.toPromise()
.then(res => this.books = res as Book[]);}

错误仍然出现在控制台上:

从源 'http://localhost:4200' 访问 'https://localhost:44302/api/books' 处的 XMLHttpRequest 已被 CORS 策略阻止:所请求的资源上不存在 'Access-Control-Allow-Origin' header .

在浏览器 (https://localhost:44302/api/books) 中打开我的 API 时,所有数据都正确显示。

根据docs

The call to UseCors must be placed after UseRouting, but before UseAuthorization. For more information, see Middleware order.

所以只需更改 Configure 方法中调用方法的顺序即可。

根据评论更新

同时删除原处的尾部斜杠。例如:WithOrigins("http://localhost:4200") 而不是 WithOrigins("http://localhost:4200/")

CORS header 需要协议和域 (http://localhost:4200),而不是端点 (http://localhost:4200/)。

services.AddCors(x => x.AddDefaultPolicy(builder => {
            builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
        }));

试试这个