【问题标题】:Script.Render(absolute or partial path) is not disabling the bundling for compilation debug=trueScript.Render(absolute or partial path) 没有禁用编译 debug=true 的捆绑
【发布时间】:2014-02-27 08:40:21
【问题描述】:

你们有谁知道为什么 Script.Render 不禁用包编译 debug ="true" 当包路径不相对于根文件夹时

我正在使用到根目录的相对路径创建捆绑包(此路径类型是强制性的,否则将引发异常):

Bundle jsBundle = new ScriptBundle("~/bundles/myscripts/");

但是当我尝试渲染它时,我需要提供完整的网址,如下所示:

Scripts.Render("http://myserver/bundles/myscripts/")

并且无论编译调试模式如何,都会启用捆绑包。

任何想法我缺少什么?

我的问题与this question 非常相关 - 我正在以这种方式渲染我的包 - 现在:编译 debug="true" 时如何禁用它?

有什么想法吗?

谢谢! 奥维

【问题讨论】:

  • 当您尝试提供相对路径时,您的代码是什么?
  • 您好 jbbi,当我在 Application_Start 中创建包时,问题的第一行代码是问题的第一行,当我尝试渲染它时类似于<%: Scripts.Render("protocol://myserver/bundles/vxscripts/") %>。我使用这种语法是因为捆绑包通过 e CDN 并且我需要完整的 URL。
  • 但是无论如何,一旦我不在 Scripts.Render 中使用 ~ 字符,我就不能再使用编译调试模式禁用捆绑包。这是我的问题,如何自定义此行为以便能够使用部分路径或完整 URL 作为路径,并且仍然让编译调试模式决定是否启用捆绑。
  • 你不是在像这样的地方强迫它 BundleTable.EnableOptimizations = true; ?
  • Ondrej,不,我不使用 EnableOptimizations=true。

标签: c# asp.net asp.net-mvc system.web.optimization


【解决方案1】:

回答我自己的问题:如果捆绑网址作为完整网址提供,则 Scripts.Render 不会根据编译模式切换捆绑:

Scripts.Render("http://myserver/bundles/myscripts/")

我采用的方法是创建自己的 mvc 助手来渲染包:

public MvcHtmlString BundleScript(string bundleUrl)
{
        var javascriptBuilder = new StringBuilder();
        bool filesExist = false;
        bool isDynamicEnabled = IsDynamicEnabled();

        if (!isDynamicEnabled)
        {
            IEnumerable<string> fileUrls = GetBundleFilesCollection(bundleUrl);
            string rootVirtualDirectory = "~/content/js/";

            if (fileUrls != null)
            {
                foreach (string fileUrl in fileUrls)
                {
                    javascriptBuilder.Append(new ScriptTag().WithSource(GetScriptName(fileUrl, rootVirtualDirectory)).ToHtmlString());
                }
                filesExist = true;
            }
        }

        if (isDynamicEnabled || !filesExist)
        {
            javascriptBuilder.Append(new ScriptTag().WithSource(bundleUrl).ToHtmlString());
        }
        return MvcHtmlString.Create(javascriptBuilder.ToString());
}

private IEnumerable<string> GetBundleFilesCollection(string bundleVirtualPath)
{
        var collection = new BundleCollection { BundleTable.Bundles.GetBundleFor(bundleVirtualPath) };
        var bundleResolver = new BundleResolver(collection);
        return bundleResolver.GetBundleContents(bundleVirtualPath);
}

private bool IsDynamicEnabled()
{
        return BundleTable.EnableOptimizations;
}
private static string GetScriptName(string scriptUrl, string virtualDirectory)
{
        return scriptUrl.Replace(virtualDirectory, string.Empty);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 2015-08-18
    相关资源
    最近更新 更多