首页 > 解决方案 > 如何使用 src 属性在 html 中打开安全 url

问题描述

我在 Azure 上托管了一个 API,它比较两个 pdf 文件并生成一个新的结果 pdf。我想使用嵌入标签在我的 html 网页中打开生成的 pdf。当我将 kudu 文件 url 放入 embed 标签的 src 属性中时,由于安全原因,它无法打开。当我使用 src="username:password@testpdfcomparison.scm.azurewebsites.net/api/vfs/site/wwwroot/pdf/Output.pdf" 时,我在浏览器中收到此错误:

阻止其 URL 包含嵌入式凭据(例如https://user:pass@host/)的子资源请求。有关更多详细信息,请参阅https://www.chromestatus.com/feature/5669008342777856

其实我想用静默登录打开这个pdf文件。我可以通过 jquery 或 c# 以任何其他方式做到这一点吗

这是 pdf 文件链接: https ://testpdfcomparison.scm.azurewebsites.net/api/vfs/site/wwwroot/pdf/Output.pdf

标签: c#htmljqueryazure-web-app-servicekudu

解决方案


我不知道为什么你的.pdf文件路径包含scm.

无论你的程序使用什么语言代码,生成的pdf文件,存放在当前运行环境下的某个文件夹中,都必须使用相对路径。(如果文件很多,建议使用azure存储)

azure webapp 中的文件路径包含scm,所以必须进行授权验证。比如你提供的文档链接,我的账号没有权限访问。如下所示。

在此处输入图像描述

实际上,Azure 应用服务本质上是一个iis. 当我们编写代码时,需要存储文件。建议使用relative paths。文件路径如下,我的示例代码是.net core 3.0.

在此处输入图像描述

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Html")),
            RequestPath = "/Html"
        });
        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "PDF")),
            RequestPath = "/PDF"
        });
        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "api")),
            RequestPath = "/api"
        });
        app.UseRouting();

        app.UseAuthorization();

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

您可以下载我的示例代码并进行部署。您可以访问以下两个网址。

  1. https://yourwebsitename.azurewebsites.net/Html/a.html.
  2. https://yourwebsitename.azurewebsites.net/api/vfs/site/wwwroot/pdf/testpdf.pdf.

在此处输入图像描述

在此处输入图像描述


推荐阅读