使用ASP.NET 4.5 Bundling和CDN(例如CloudFront)

Mr.*_*ble 33 c# amazon-cloudfront asp.net-4.5 bundling-and-minification

ASP.NET 4.5具有很好的新捆绑功能,似乎对CDN的使用有一些支持.Microsoft提供的使用CDN捆绑功能的示例就是这样

public static void RegisterBundles(BundleCollection bundles)
{
  //bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
  //            "~/Scripts/jquery-{version}.js"));

  bundles.UseCdn = true;   //enable CDN support

  //add link to jquery on the CDN
  var jqueryCdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js";

  bundles.Add(new ScriptBundle("~/bundles/jquery",
            jqueryCdnPath).Include(
            "~/Scripts/jquery-{version}.js"));

  // Code removed for clarity.
} 
Run Code Online (Sandbox Code Playgroud)

这似乎暗示您需要明确告诉它CDN上文件的路径.

CloudFront CDN(我假设许多其他人)为您提供了一个镜像您自己的子域.什么时候你打http://uniquesubdomain.cloudfront.net/js/myfile.js?v=1它起来http://mydomain.com/js/myfile.js?v=1

这样,您可以简单地为所有链接添加前缀,http://uniquesubdomain.cloudfront.net/并且您的文件是来自CloudFront的服务器.

ASP.NET 4.5捆绑功能是否与此类CDN兼容?是否有一种内置方法可以将捆绑功能的所有链接作为CDN域的前缀?

例如.

bundles.UseCdn = true;
var myBundle= new ScriptBundle("~/bundles/js", "https://uniquedomain.cloudfront.net/");
myBundle.Include("~/js/file1.js");
myBundle.Include("~/js/file2.js");
Run Code Online (Sandbox Code Playgroud)

会导致

    <script src="https://uniquedomain.cloudfront.net/bundles/js?v=6y-qVPSK3RYOYHfPhOBDd92H4LjEjs-D3Hh2Yml6CXA1"></script>
Run Code Online (Sandbox Code Playgroud)

Bri*_*nga 9

此功能不是内置的,但可以使用几个小帮助方法.这就是我现在正在使用的:

public static class Cdn
{
    private const string CdnRoot = "//cloudfrontdomainhere.com";

    private static bool EnableCdn
    {
        get
        {
            bool enableCdn = false;
            bool.TryParse(WebConfigurationManager.AppSettings["EnableCdn"], out enableCdn);
            return enableCdn;
        }
    }

    public static IHtmlString RenderScripts(string bundlePath)
    {
        if (EnableCdn)
        {
            string sourceUrl = CdnRoot + Scripts.Url(bundlePath);
            return new HtmlString(string.Format("<script src=\"{0}\"></script>", sourceUrl));
        }

        return Scripts.Render(bundlePath);
    }

    public static IHtmlString RenderStyles(string bundlePath)
    {
        if (EnableCdn)
        {
            string sourceUrl = CdnRoot + Styles.Url(bundlePath);
            return new HtmlString(string.Format("<link href=\"{0}\" rel=\"stylesheet\" />", sourceUrl));
        }

        return Styles.Render(bundlePath);
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我在配置文件的appSettings部分中有自己的配置设置EnableCdn.从Razor视图调用时,会产生正确的输出,将CDN域附加到路径上.

在你的Razor文件中只需做Cdn.RenderScripts("〜/ pathtoscriptbundle")


oro*_*edd 1

可能不完全是您正在寻找的内容,但许多 CDN 现在都使用 DNS 充当反向代理,因此您不必显式链接您的资产。我知道 Cloudflare 会这样做,我相信其他人也会这样做。

  • SSL 现在甚至适用于 Cloudflare 上的免费计划。 (2认同)