【问题标题】:ASP Net Web API is blocking requests due to CORS policy [duplicate]由于 CORS 策略,ASP Net Web API 正在阻止请求[重复]
【发布时间】:2020-04-14 06:31:58
【问题描述】:

我正在尝试将一些请求从我的 Angular 应用程序发送到我的 ASP.NET Web API

服务器,但请求因 CORS 政策而被阻止。

错误信息:

在 'localhost:5000/api/admins/' 从源访问 XMLHttpRequest 'http://localhost:4200' 已被 CORS 策略阻止:跨源 请求仅支持协议方案:http、data、chrome、 chrome 扩展,https。

我已经尝试允许任何主机、标头和方法,但问题仍然存在。

这是我的 CORS 政策:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(myAllowSpecificOrigins,
        builder =>
        {
            builder.AllowAnyOrigin();
            builder.AllowAnyHeader();
            builder.AllowAnyMethod();
        });
    });
    services.AddMvc(options => options.EnableEndpointRouting = false);
    services.AddControllers();
}

我的 Angular 应用在​​ localhost:4200 上运行,我的服务器在 localhost:5000 上运行。

我很高兴收到任何建议。

【问题讨论】:

    标签: asp.net-web-api cors


    【解决方案1】:

    我认为您已经完成了 CORS 策略所需的配置,并在您的应用程序中添加了新策略 myAllowSpecificOrigins,但您还需要启用它才能使用

    可以在Configure方法中启用

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        ...
        app.UseCors(myAllowSpecificOrigins); //use the policy added in ConfigureServices
        app.UseMvc();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-13
      • 1970-01-01
      • 2022-01-14
      • 2021-02-28
      • 2021-05-19
      • 2019-11-30
      • 2019-10-01
      • 2019-07-01
      • 2020-06-02
      相关资源
      最近更新 更多