You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular结合ASP.Net Core使用ngx-extended-pdf-viewer报CORS错误

ASP.NET Core + Angular ngx-extended-pdf-viewer 跨域问题排查

问题场景

在ASP.NET Core为后端的Angular项目中,使用ngx-extended-pdf-viewer组件实现PDF预览功能时,触发浏览器CORS跨域拦截。

原有配置代码

Angular组件模板

<ngx-extended-pdf-viewer [src]="pdfsrc" 
                        [height]="'95%'"
                        useBrowserLocale="true"
                        [textLayer]="true"
                        [showHandToolButton]="true"
                        >
                    </ngx-extended-pdf-viewer>

Angular组件逻辑

pdfsrc: any;
this.pdfsrc = this.children.studyPath;
this.sanitizer.bypassSecurityTrustResourceUrl(this.pdfsrc)

后端CORS配置

app.UseCors(policy => policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200"));

报错信息

从源https://localhost:4200请求https://localhost:5001/ChildStudyReportFolder/7a6c78dd-aa3a-46db-bbea-37a456784d1a.pdf时被CORS策略拦截:被请求资源未携带Access-Control-Allow-Origin响应头。
错误原文:'https://localhost:5001/ChildStudyReportFolder/7a6c78dd-aa3a-46db-bbea-37a456784d1a.pdf' from origin 'https://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

排查解决步骤

  • 修正ASP.NET Core中间件注册顺序:这是该问题最常见的诱因。CORS中间件必须放在UseStaticFiles之前注册,否则静态PDF文件请求会被静态文件中间件直接返回,完全不经过CORS逻辑,自然不会携带跨域响应头。正确的中间件顺序参考:
    var builder = WebApplication.CreateBuilder(args);
    // 先注册CORS服务
    builder.Services.AddCors();
    var app = builder.Build();
    
    // 1. 最先注册CORS中间件
    app.UseCors(policy => policy
        .AllowAnyHeader()
        .AllowAnyMethod()
        .WithOrigins("https://localhost:4200")
        // 如果组件带凭证请求可以放开这行,注意生产环境不要和通配源搭配使用
        // .AllowCredentials()
    );
    // 2. 再注册静态文件中间件,保证静态资源请求也经过CORS校验
    app.UseStaticFiles();
    // 3. 后续再注册其他中间件
    app.UseRouting();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
    
  • 修正Angular端安全资源URL赋值逻辑:当前代码调用bypassSecurityTrustResourceUrl后没有接收返回值,等于安全绕过逻辑未生效,修改组件代码:
    import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
    
    // 字段类型改为安全资源URL类型
    pdfsrc: SafeResourceUrl;
    
    // 赋值时接收bypass方法的返回值
    this.pdfsrc = this.sanitizer.bypassSecurityTrustResourceUrl(this.children.studyPath);
    
  • 校验静态文件目录配置:确认ChildStudyReportFolder目录已经被正确配置为静态文件服务目录,且PDF文件路径访问不需要额外鉴权逻辑拦截。如果自定义了静态文件授权规则,需要保证CORS中间件在授权逻辑前执行。
  • 部署环境校验:如果使用IIS、Nginx等反向代理托管应用,检查代理层是否配置了覆盖响应头的规则,避免代理层删掉Access-Control-Allow-Origin头。

内容的提问来源于stack exchange,提问作者King Genius

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 20:48:35