Asp.Net MVC Bundling,检测丢失文件的最佳方法

ton*_*ony 14 asp.net-mvc

我刚刚追了一个由于缺少javascript文件而导致的错误,它无声地失败了.

该文件的缩小版本存在但不是完整版本,客户端上没有呈现链接(我期待),但我也没有例外.我想知道文件是否不存在.

(为了清楚,捆绑包没有尝试包含缩小版本,它试图包含完整版本,但是缩小版本存在于脚本目录中)

我是否必须编写自定义内容以检测此内容,或者MVC是否内置了任何内容来报告此内容?

谢谢

Her*_*Kan 27

我开始使用以下扩展方法Bundle:

public static class BundleHelper
{
    [Conditional("DEBUG")] // remove this attribute to validate bundles in production too
    private static void CheckExistence(string virtualPath)
    {
        int i = virtualPath.LastIndexOf('/');
        string path = HostingEnvironment.MapPath(virtualPath.Substring(0, i));
        string fileName = virtualPath.Substring(i + 1);

        bool found = Directory.Exists(path);

        if (found)
        {
            if (fileName.Contains("{version}"))
            {
                var re = new Regex(fileName.Replace(".", @"\.").Replace("{version}", @"(\d+(?:\.\d+){1,3})"));
                fileName = fileName.Replace("{version}", "*");
                found = Directory.EnumerateFiles(path, fileName).FirstOrDefault(file => re.IsMatch(file)) != null;
            }
            else // fileName may contain '*'
                found = Directory.EnumerateFiles(path, fileName).FirstOrDefault() != null;
        }

        if (!found)
            throw new ApplicationException(String.Format("Bundle resource '{0}' not found", virtualPath));
    }

    public static Bundle IncludeExisting(this Bundle bundle, params string[] virtualPaths)
    {
        foreach (string virtualPath in virtualPaths)
            CheckExistence(virtualPath);

        return bundle.Include(virtualPaths);
    }

    public static Bundle IncludeExisting(this Bundle bundle, string virtualPath, params IItemTransform[] transforms)
    {
        CheckExistence(virtualPath);
        return bundle.Include(virtualPath, transforms);
    }
}
Run Code Online (Sandbox Code Playgroud)

这样您就不必PreCheck()显式调用助手方法.它还支持ASP.NET的通配符{version}和*:

bundles.Add(new ScriptBundle("~/test")
    .IncludeExisting("~/Scripts/jquery/jquery-{version}.js")
    .IncludeExisting("~/Scripts/lib*")
    .IncludeExisting("~/Scripts/model.js")
    );
Run Code Online (Sandbox Code Playgroud)