c# - 将 CDN 网址添加到 mvc 4 bundler 输出

标签 c# asp.net-mvc-4 cdn bundling-and-minification

使用内置的 MVC4 bundler ,我如何将我的 CDN url 添加到它生成的链接标签?我已经设置了 Amazon Cloudfront,以便它在第一次请求时从我的网络服务器中提取 Assets 。所以当我像这样定义一个包时:

 bundles.Add(new StyleBundle("~/Content/css").Include(
    "~/Content/reset.css",
    "~/Content/960_24_col.css",
    "~/Content/Site.css"
 ));

部署后,我可以这样引用它:

http://[cloundfrontid].cloudfront.net/Content/css?v=muhFMZ4thy_XV3dMI2kPt-8Rljm5PNW0tHeDkvenT0g1

现在我只需要将 bundler 生成的链接从相对链接更改为指向我的 CDN 的绝对链接。

  <link href="[INSERT_CDN_URL_HERE]/Content/css?v=muhFMZ4thy_XV3dMI2kPt-8Rljm5PNW0tHeDkvenT0g1" rel="stylesheet"/>

我认为可以使用 IBundleTransform 重写路径,但我找不到任何这样的例子。

注意: 需要明确的是,我知道您可以为 bundle 指定 CDN 链接,但这仅在 bundle 可以由静态链接替换时才有效。

最佳答案

我刚刚设置了 MaxCDN 并遇到了同样的问题。

如您所知,bundles.UseCdn 属性并不理想,因为我们不想为包指定确切的 url。像 Max CDN 这样的 CDN 是完全相同的 url、查询字符串和所有内容,除了不同的子域。

这是我最终解决它的方法。

我创建了一个 BundleHelper 类,它将包装 render 方法,然后在路径前加上 CDN 子域。

类是这样的:

namespace MyDomain.Web.Helpers
{
    public class BundleHelper
    {
        public static string CdnPath = "http://cdn.mydomain.com";

        public static IHtmlString RenderScript(string path)
        {
            var opt = System.Web.Optimization.Scripts.Render(path);
            string htmlString = HttpUtility.HtmlDecode(opt.ToHtmlString());

            if (BundleTable.EnableOptimizations)
            {
                htmlString = htmlString.Replace("<script src=\"/", String.Format("<script src=\"{0}/", CdnPath));
            }

            return new HtmlString(htmlString);
        }

        public static IHtmlString RenderStyle(string path)
        {
            var opt = System.Web.Optimization.Styles.Render(path);
            string htmlString = HttpUtility.HtmlDecode(opt.ToHtmlString());

            if (BundleTable.EnableOptimizations)
            {
                htmlString = htmlString.Replace("<link href=\"/", String.Format("<link href=\"{0}/", CdnPath));
            }

            return new HtmlString(htmlString);
        }
    }
}

然后要在 View 中使用它,我只需这样做:

@BundleHelper.RenderStyle("~/Content/css")
@BundleHelper.RenderStyle("~/Content/themes/base/css")

@BundleHelper.RenderScript("~/bundles/jquery")
@BundleHelper.RenderScript("~/bundles/jqueryui")

希望这对您有所帮助。

关于c# - 将 CDN 网址添加到 mvc 4 bundler 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14838442/

相关文章:

caching - 强制内容更新到云端,不使用无效

c# - 确定 AccessViolationException DragDrop.DoDragDrop 的原因

asp.net-mvc - Ajax.Actionlink 无法与 Telerik MVC Grid 一起使用

asp.net-mvc-4 - 如何从ASP.NET MVC 4中的数据库填充下拉列表

web-hosting - 使用 CDN 和我们自己的服务器哪个更好?

Jquery Migrate CDN 回退条件

c# - 如何使用 string.Substring(char, char) 而不是 string.Substring(int, int)?

c# - .net 在文本框中大写名称

c# - 使用 Directory.GetFiles 时出现 UnauthorizedAccessException

jquery-ui - 总是收到 "The field Date must be a date"验证消息