从托管在 Asp.net 核心 Web 服务器中的 Angular 应用程序调用我的休息服务,被 CORS 策略阻止

Call to my rest service from Angular app hosted in Asp.net core web server blocked by CORS policy

我有一个 Angular 应用程序托管在 Asp.net 核心网络服务器上,虽然这个 Angular 应用程序我正在调用另一个 Rest api 服务来获取一些数据但是我对外部 Rest Service api 的调用被 CORS 策略阻止了。

我在浏览器中遇到的错误是 -

和我的 Asp.net 服务器应用程序 Startup.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace WebclientServer
{
public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit 
    https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
          options.AddPolicy("CorsPolicy",
              builder => builder.AllowAnyOrigin()
                  .AllowAnyMethod()
                  .AllowAnyHeader());
        });
        services.AddMvc();

    }

    // 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.UseRouting();

        //app.UseEndpoints(endpoints =>
        //{
        //    endpoints.MapGet("/", async context =>
        //    {
        //        await context.Response.WriteAsync("Hello World!");
        //    });
        //});

        app.UseCors("CorsPolicy");

        app.Use(async (context, next) => {
            await next();
            if (context.Response.StatusCode == 404 &&
               !Path.HasExtension(context.Request.Path.Value) &&
               !context.Request.Path.Value.StartsWith("/api/"))
            {
                context.Request.Path = "/index.html";
                await next();
            }
        });
        //app.UseMvcWithDefaultRoute();
        app.UseDefaultFiles();
        app.UseStaticFiles();
    }
  }
}

我已经从 link 阅读了有关如何在互联网上解决此错误的信息,但在我的案例中没有成功。请不要介意我是 web 开发的新手,并且在 CORS 策略错误上我已经被困了好几天了。请帮助我如何解决此错误。我还必须在我的 External Rest api 服务上启用 CORS。 谢谢!

CORS 是服务器端“问题”,而不是客户端。所以,我想,你不应该尝试在你的客户端上修复它(即 Angular 即使它托管在 X 服务器类型上)。这就是我认为您的 ASP.net 修复程序不起作用的原因。尝试在客户端修复 CORS,尽管有时可能,但大多数时候会导致错误或仅导致服务器 ignoring/blocking 请求。

最简单的方法 是在您的服务器端配置 CORS。您已指定您正在访问 外部 REST API。因此,您必须深入挖掘,而忘记客户端修复。