Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dotnet Core 3.1 cors issue when serving static image files

I host my dotnet core 3.1 API with Angular on different domain than my frontend html site. I am using jquery watermark plugin to add watermark on my images, but sometimes, the image shows normally but watermark is not added. When i checked the console, it shows errors that the access to images was blocked by CORS policy. My API are all working correctly without cors issue.

What did i do wrong in my API setup? It seems like normal static files is working but it prompt error when using canvas.toDataURL() to get images.

I configured my Startup.cs Configure method as follows:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseCors(builder => builder
         .AllowAnyOrigin()
         .AllowAnyMethod()
         .AllowAnyHeader()
         );
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
        }

        app.UseStaticFiles(new StaticFileOptions()
        {
            OnPrepareResponse = ctx => {
                ctx.Context.Response.Headers.Append("Access-Control-Allow-Origin", "*");
                ctx.Context.Response.Headers.Append("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            },
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot")),
            RequestPath = new PathString("")
        });
        if (!env.IsDevelopment())
        {
            app.UseSpaStaticFiles();
        }

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");
        });

        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }

I tried to add configurations to UseStaticFiles but it's still not working

The info below is my request header and response header

REQUEST HEADER

GET //imageUploaded/banner_002_bb9d.jpg HTTP/1.1,
Origin:,
Referer:,
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/80.0.3987.163 Safari/537.36

RESPONSE HEADER

Accept-Ranges: bytes
Content-Length: 119395
Content-Type: image/jpeg
Date: Fri, 10 Apr 2020 12:12:14 GMT
ETag: "1d600678e1fa163"
Last-Modified: Sun, 22 Mar 2020 16:33:02 GMT
Server: Microsoft-IIS/10.0
Warning: 113
X-Powered-By: ASP.NET
like image 204
Lance Avatar asked Feb 14 '26 16:02

Lance


1 Answers

I found the workable solution after some testing.

This code works app.UseStaticFiles(); for normal servings of static files. But when the static files will be downloaded with xhr request, it needs to have cors setup for it to work cross domain.

The following code is what needed to make it work

        app.UseStaticFiles(new StaticFileOptions()
        {
            OnPrepareResponse = ctx => {
                ctx.Context.Response.Headers.Append("Access-Control-Allow-Origin", "*");
                ctx.Context.Response.Headers.Append("Access-Control-Allow-Headers", 
                  "Origin, X-Requested-With, Content-Type, Accept");
            },

        });

Hope this helps

like image 82
Lance Avatar answered Feb 16 '26 17:02

Lance