【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource even after setting CORS即使在设置 CORS 后,请求的资源上也没有“Access-Control-Allow-Origin”标头
【发布时间】:2020-08-21 10:53:07
【问题描述】:

我受够了 .NET Core Web API 应用程序中的 CORS 错误。我已经完成了我认为的所有设置。

我做了什么

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddControllers();

    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseCors(options =>
            options.WithOrigins("http://localhost:4200/")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowAnyMethod());
        //app.UseCors(builder => builder
        //            .AllowAnyOrigin()
        //            .AllowAnyMethod()
        //            .AllowAnyHeader()
        //            .AllowCredentials());
        app.UseHttpsRedirection();

        app.UseRouting();

    }

即使现在它触发以下错误

从源“http://localhost:4200”访问“https://localhost:44331/api/kip”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我从 Angular 调用它

这是我的调用脚本

  getProjects() {
    let url:string=this.isServer?"http://localhost:51071/webservice1.asmx":"https://localhost:44331";
    console.info(url);
    return this.client.get(url+'/api/kip', {
      withCredentials: true,
      responseType: 'json'
    });
  }

我还在返回前在 API 的最后一行设置了一个断点,它到达那里没有任何问题。所以在调用 return 之后它会触发错误。我还单独尝试了返回 JSON 的 API。

这是我的控制器。

    // GET: api/Kip
    [HttpGet]
    public KipProjects Get()
    {
        KipProjects proj = new KipProjects();
        kip keyedin = new kip();
        proj=keyedin.getKeyedinReport();

        return proj;
    }

【问题讨论】:

  • 您是否尝试将AllowCredentials 添加到您指定来源的那个(options.WithOrigins("http://localhost:4200/"))?
  • 是的,那也试过了。但结果是一样的!
  • 嗯,可能是 UseCors 需要在 UseRouting 之后:docs.microsoft.com/en-us/aspnet/core/security/…

标签: angular asp.net-core asp.net-web-api


【解决方案1】:

请参考document

注意:指定的 URL 不能包含尾部斜杠 (/)。如果 URL 以 / 结尾,则比较返回 false 并且不返回任何标头。

所以试试options.WithOrigins("http://localhost:4200")

【讨论】:

    猜你喜欢
    • 2017-02-07
    • 1970-01-01
    • 2014-07-06
    • 2017-04-11
    • 2022-07-28
    • 2023-03-16
    • 2014-07-30
    • 2016-01-14
    • 2023-03-15
    相关资源
    最近更新 更多