【问题标题】:Dotnet Core 3.1 cors issue when serving static image files提供静态图像文件时的 Dotnet Core 3.1 cors 问题
【发布时间】:2020-07-23 22:09:13
【问题描述】:

我使用 Angular 在与我的前端 html 网站不同的域上托管我的 dotnet core 3.1 API。 我正在使用 jquery watermark 插件在我的图像上添加水印,但有时图像显示正常但没有添加水印。当我检查控制台时,它显示对图像的访问被 CORS 策略阻止的错误。我的 API 都可以正常工作,没有 cors 问题。

我在 API 设置中做错了什么?看起来正常的静态文件正在工作,但是在使用 canvas.toDataURL() 获取图像时会提示错误。

我将我的 Startup.cs 配置方法配置如下:

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");
            }
        });
    }

我尝试将配置添加到 UseStaticFiles 但是还是不行

下面的信息是我的请求头和响应头

请求标头

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

响应标题

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

【问题讨论】:

    标签: jquery angular .net-core cors watermark


    【解决方案1】:

    在 dotnet core 3.1 中,默认情况下,当我们要提供 css、js 或图像等任何静态文件时,这些文件应位于 wwwroot 目录中,您只需使用以下函数即可。

    app.UseStaticFiles();
    

    如果这些文件位于 wwwroot 以外的不同目录中,则需要提供 StaticFileOptions() 实例。

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

    更多详情,请阅读:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

    【讨论】:

    • 谢谢,但在此之前我只使用app.UseStaticFiles();,但我也遇到了同样的问题,我通过参考其他指南复制了 StaticFileOptions 部分
    【解决方案2】:

    经过一些测试,我找到了可行的解决方案。

    此代码适用于app.UseStaticFiles(); 用于静态文件的正常服务。但是当使用 xhr 请求下载静态文件时,需要设置 cors 才能跨域工作。

    下面的代码是让它工作所需要的

            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");
                },
    
            });
    

    希望对你有帮助

    【讨论】: