首页 > 解决方案 > Angular 前端和 webapi .NET core 5.0 之间的跨域请求被阻止

问题描述

我有 .NET core 5.0 webapi,需要从 Angular 应用程序中使用,它们都在同一台机器上运行。

我得到的错误是:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/Game/GetPossibleMoves. (Reason: CORS request did not succeed).

我做了什么/尝试了什么

  1. 阅读并尝试应用 SO 的其他答案
  2. 在后端 .NET core 5.0 上启用 CORS
  3. 在前端 Angular 中包含 httpOptions
  4. 禁用windows防火墙(不是原因)

在我尝试过的 ConfigureServices 中:

/* attempt 1
services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    //builder.WithOrigins("http://example.com", "http://www.contoso.com");
                    //This is done this way to facilitate connecting frontend and backend
                    //but this should be changed to enforce certain origins or methods
                    builder.AllowAnyOrigin(). ;
                });
        });
*/

/* attempt 2 
services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
{
    builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader();
}));
*/

services.AddCors(c =>  
{  
    c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());  
});  

services.AddControllers();

在配置方法中

        app.UseRouting();
        //app.UseCors("ApiCorsPolicy");
        app.UseCors(options => options.AllowAnyOrigin());  

在 Angular 中,我尝试在 API 上调用 GET

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class BackendService {
  private readonly getMovesURL = 'http://localhost:5000/api/Game/GetPossibleMoves';

  private httpOptions: any;
  
  constructor(private http: HttpClient) { 
    this.httpOptions = {
      observe: 'body', 
      responseType: 'json',
      /*
      headers: new HttpHeaders({ 
        'Access-Control-Allow-Origin':'*'
      })
      */
      headers:{'Access-Control-Allow-Origin':'*'}
    };
  }

  getGameMoves(): Observable<any> {
    console.log('calling: GetPossibleMoves');

    return this.http.get<string[]>(this.getMovesURL, this.httpOptions);
  }
}

我也尝试过没有任何标题,无论我尝试哪种组合,包括在 SO 中回答非常相似的问题。总是返回这些错误

跨域请求被阻止:同源策略不允许读取位于 http://localhost:5000/api/Game/GetPossibleMoves 的远程资源。(原因:CORS 请求未成功)。

在此处输入图像描述

标签: angular.net-corecors

解决方案


管道的顺序放在app.UseCors();您的顶部Configure()

在有角度的一侧移除headers:{'Access-Control-Allow-Origin':'*'}以解决:

跨域请求被阻止:同源策略不允许读取位于 http://localhost:5000/api/Game/GetPossibleMoves 的远程资源。(原因:根据 CORS 预检响应中的标头“Access-Control-Allow-Headers”,标头“access-control-allow-origin”是不允许的)。


推荐阅读