首页 > 解决方案 > EF CORE API 仅在 html2canvas 中不添加 access-control-allow-origin 响应标头

问题描述

我的问题是,当 html2canvas 尝试渲染一张图像时,它无法告诉我 cors 策略存在问题。我检查了请求,发现响应标头上不存在 access-control-allow-origin。

我在我的 Startap.cs 和我的 api 的 Configure() 方法中添加了这段代码:

app.Use((context, next) =>
            {
                context.Response.Headers["Access-Control-Allow-Origin"] = "*";
                return next.Invoke();
            });

上面的代码将 Access-Control-Allow-Origin 添加到所有响应标头,但 HTML2canvas 尝试获取图像时除外。

请记住,只有当 html2cavas 尝试从 api 获取图像时,我才会遇到 cors 的这个问题。

其他一切工作正常。

任何人都可以帮忙吗?

这是前端代码:

html2canvas(data, {logging: true, allowTaint: false, useCORS: true }).then(canvas => {
        // var imgWidth = 220;
        // var pageHeight = 320;
        var imgWidth = 280; // valor anterior: 280
        var pageHeight = 1000; //valor anterior: 1000
        var imgHeight = canvas.height * imgWidth / canvas.width;
        //var imgHeight = 2000;
        var heightLeft = imgHeight;
        var widthLeft = imgWidth;

        const contentDataURL = canvas.toDataURL('image/png');
        let pdf = new jspdf('landscape', 'mm', 'a4', true); // A4 size page of PDF
        var position = 0;
        pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight, '', 'FAST');

        pdf.save('PadronTecnico.pdf'); // Generated PDF
        this.blockUI.stop();

        this.showScrolls = true;
     })

标签: angularasp.net-corehtml2canvas

解决方案


我在 Configure() 方法上添加了响应标头,它运行良好!

app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Resources")),
                RequestPath = new PathString("/Resources"),
                OnPrepareResponse = ctx =>
                {
                    ctx.Context.Response.Headers.Append("Access-Control-Allow-Origin", "*");
                }
            });

推荐阅读