asp core 和 angular7 中没有 'Access-Control-Allow-Origin' header

No 'Access-Control-Allow-Origin' header in asp core and angular7

我需要从后端 Asp Core 2.2 下载图像并在 Angular 中显示。

我在 angular 中创建一个用于显示图像的组件:

在Html代码:

<img [src]="src$ | async" class="img-fluid img-thumbnail">

在 Ts 文件中:

  @Input() ImagePath: string;
  ImageBlob: any;

  public src$: Observable<SafeUrl>;
  private imageSrc$: BehaviorSubject<string>;

  constructor(private downloadService: DownloadService, private domSanitizer: DomSanitizer) {
    this.imageSrc$ = new BehaviorSubject(null);
    this.src$ = this.imageSrc$.pipe(switchMap(src => this.getImage(this.ImagePath)));
  }

  ngOnChanges() {
    this.imageSrc$.next(this.ImagePath);
  }

  private createImage(blob: Blob) {
    console.log('CREATE_IMAGE');
    return this.domSanitizer.bypassSecurityTrustUrl(URL.createObjectURL(blob));
  }

  private getImage(url: string) {
    console.log('GET_IMAGE');
    return this.downloadService
      .DownloadImage(this.ImagePath)
      .pipe(map((blob: Blob) => this.createImage(blob)));
  }
}

并在服役中:

DownloadImage(ImageUrl: string): Observable<Blob> {
    return this.httpClient.get(ImageUrl, { responseType: 'blob' });
 }

现在,当我需要显示图像时,它会在控制台中显示此错误:

Access to XMLHttpRequest at 'https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/903797628068313.jpg' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

GET http://localhost:4200/null 404 (Not Found)

这是我的拦截器:

   @Injectable()
export class RequestInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (req.url.includes('/Upload/')) {
            console.log('upload')
            req = req.clone({ headers: req.headers.set('Access-Control-Allow-Origin', '*') })
            return next.handle(req);
        }
        if (!req.headers.has('Content-Type')) {
            console.log('type')
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }
        req = req.clone({ headers: req.headers.set('Access-Control-Allow-Origin', '*') })
        req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
        return next.handle(req);
    }
}

不知道问题出在哪里?在前端还是后端 ??

这是 Asp 核心中的启动:

services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                  .AllowAnyMethod()
                  .AllowAnyHeader()
                  .WithOrigins("http://localhost:4200")
                  .AllowCredentials()
            .Build());

        });

问题出在哪里?我该如何解决这个问题????

ASP.NET Core 2.2 不允许 AllowAnyOriginAllowCredentials 的组合。您需要将 AllowAnyOrigin 更改为 SetIsOriginAllowed:

app.UseCors(builder => builder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .SetIsOriginAllowed((host) => true)
                .AllowCredentials()
            );

虽然另一个答案是正确的,但如果您想要定义特定的允许来源(您应该这样做),您应该从 CORS 语句中删除 .AllowAnyOrigin()SetIsOriginAllowed((host) => true) ,它将与.AllowCredentials().

        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder
                  .AllowAnyMethod()
                  .AllowAnyHeader()
                  .WithOrigins("http://localhost:4200")
                  .AllowCredentials()
            .Build());

        });

如果你想允许多个 Origins,你可以设置一个 origins 数组并将其用作 .WithOrigins() 中的参数。例如:

private readonly string[] MyAllowedOrigins = new string[] {
    "http://localhost:4200",
    "http://localhost:3000"
};

...
.WithOrigins(MyAllowedOrigins)
...

此外,请注意使用的方案 - 检查它是 http 还是 https

为了完整起见,永远不要忘记添加例如app.UseCors("CorsPolicy"); 您在哪里配置管道,例如.Configure Startup 中的方法 class.


总而言之 - 虽然在某些情况下允许任何来源都可以,但您通常希望并且应该明确定义允许的来源。

关于 SetIsOriginAllowed((host) => true) - 这应该是一个表达式来评估是否应该允许来源,使其始终 return => true,在开发人员下可能没问题。环境,但据我所知不应在生产中使用。

您可以在 MS Docs 上找到很好的读物。结帐: