加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – Asp.Net MVC捆绑,最好的方式来检测丢失的文件

发布时间:2020-12-15 22:19:56 所属栏目:asp.Net 来源:网络整理
导读:我刚刚追赶了一个由于缺少的 javascript文件造成的错误,它是默默无声的. 文件的最小化版本存在但不是完整版本,一个链接不会呈现在客户端(我期待的),但是我也没有得到例外.我想知道文件是否不存在. (只是为了清楚,捆绑包没有尝试包括最小化的版本,它试图包括
我刚刚追赶了一个由于缺少的 javascript文件造成的错误,它是默默无声的.

文件的最小化版本存在但不是完整版本,一个链接不会呈现在客户端(我期待的),但是我也没有得到例外.我想知道文件是否不存在.

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

我必须写一些自定义的东西来检测这个,或者MVC有什么内置的来报告?

谢谢

解决方法

我想起了对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).Where(file => re.IsMatch(file)).FirstOrDefault() != 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);
    }
}

这样你就不必明确地调用你的帮助方法PreCheck().它还支持ASP.NET的通配符{version}和*:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读