首页 > 解决方案 > 提供静态图像文件时的 Dotnet Core 3.1 cors 问题

问题描述

我在与我的前端 html 站点不同的域上使用 Angular 托管我的 dotnet core 3.1 API。我正在使用jquery水印插件在我的图像上添加水印,但有时图像显示正常但没有添加水印。当我检查控制台时,它显示对图像的访问被 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

标签: jqueryangular.net-corecorswatermark

解决方案


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

此代码适用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");
            },

        });

希望这可以帮助


推荐阅读