【问题标题】:How can I include SRI hash in ScriptBundle for .NET MVC (4.7.2) application?如何在 ScriptBundle for .NET MVC (4.7.2) 应用程序中包含 SRI 哈希?
【发布时间】:2021-07-15 12:54:25
【问题描述】:

目前我的包正在使用公共库的本地副本。

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/moment.min.js",
                      "~/Scripts/bootstrap-datetimepicker.min.js",
                      "~/Scripts/respond.js"));

我想转换为使用 CDN,并希望通过包含哈希值来确保我遵守 SRI。我发现很多关于在捆绑配置中使用 CDN 的文章,但没有关于如何在捆绑时包含 SRI 哈希和跨域标记。

请帮助我。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 subresource-integrity


    【解决方案1】:

    试试下面的代码:

    bundles.UseCdn = true; bundles.Add(new ScriptBundle("~/bundles/jquery", "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js").Include( "~/Scripts/jquery-{version}.js"));

    并以 debug="false" 模式运行您的应用程序或使用 BundleTable.EnableOptimizations = true;

    【讨论】:

    • 这不会产生所需的哈希值。
    【解决方案2】:

    试试这个:

     public static void RegisterBundles(BundleCollection bundles)
     {
        BundleTable.EnableOptimizations = true;
        string version = string.Format("{0}", DateTime.Now.ToString("yyyyMMddHHmmss"));
        bundles.UseCdn = true;
        var cdnUrl = "CDN url"+ "{0}?" + version;
        
        bundles.Add(new ScriptBundle("~/bundles/bootstrap", string.Format(cdnUrl, "bundles/bootstrap")).Include(
                          "~/Scripts/bootstrap.js",
                          "~/Scripts/moment.min.js",
                          "~/Scripts/bootstrap-datetimepicker.min.js",
                          "~/Scripts/respond.js"));
     
     }
    

    并在Global.asax.cs 内的Application_BeginRequest 中添加此行以允许跨域

    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "CDN url");
    

    【讨论】:

    • 请您解释一下
    猜你喜欢
    • 2021-01-06
    • 2020-12-21
    • 2016-11-16
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    相关资源
    最近更新 更多