3

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
Lance
  • 307
  • 4
  • 14

2 Answers2

13

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

Lance
  • 307
  • 4
  • 14
  • 1
    Thanks. This is exactly what I needed. – Mifo Nov 11 '20 at 19:58
  • 1
    Here is a link to a page about reusing the policy that you created for your endpoints: https://www.bytefish.de/blog/aspnetcore_static_files_cors.html – Jon McEroy Feb 19 '21 at 20:20
-2

In dotnet core 3.1, by default when we want to serve any static file like css, js or images, these files should be in wwwroot directory and you need to only use below function.

app.UseStaticFiles();

if these files are in different directory other than wwwroot, then you need to provide StaticFileOptions() instance.

app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")),
RequestPath = "/StaticFiles" });

For more details, read here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

Jayesh Tanna
  • 398
  • 5
  • 17
  • Thanks, But i am using just `app.UseStaticFiles();` before this but im having the same issue as well i copied the **StaticFileOptions** part by referring to other guides – Lance Apr 11 '20 at 06:52