0

I am trying to view pdf file using ngx-extended-pdf-viewer in angular with ASP.net Core as backend. This is my template:

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

in my component.ts

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

CORS policy in ASP.Net Core

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

I am getting this error Access to fetch at

'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.

King Genius
  • 51
  • 1
  • 1
  • 6

2 Answers2

0

the issue was that app.UseStaticFiles(); was placed before use app.UseCors() in the startup.cs;

After placing app.UseStaticFiles() after app.UseCors(); I cleared all cache data and it works. Thanks

King Genius
  • 51
  • 1
  • 1
  • 6
-1

It may help if you could show more details, Enable CORS in ASP.NET Core,you should set as below :

public void ConfigureServices(IServiceCollection services)
    {
        ........
        services.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                              policy =>
                              {
                                  policy.WithOrigins("......");
                              });
        });
        ......
    }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        ......
        app.UseRouting();
        ......

        app.UseCors(MyAllowSpecificOrigins);

        ......

        app.UseAuthorization();

        ......
    }

notice the order of the middleware,app.UseCors(MyAllowSpecificOrigins);should behind app.UseRouting();and beforeapp.UseAuthentication();

add [EnableCors] on your controller

The offcial document related: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0

Ruikai Feng
  • 6,823
  • 1
  • 2
  • 11
  • I am able to fetch data from the backend by angular, meaning the CORS is working, it is only fetching the pdf that I am having the COR issue – King Genius Jun 16 '22 at 09:45