gpt4 book ai didi

asp.net-mvc - 方法 "Bundle.Include"(在与 ASP.NET MVC 一起使用的 System.Web.Optimization 中)是否可以抛出异常而不是默默地忽略丢失的文件?

转载 作者:行者123 更新时间:2023-12-02 11:07:38 25 4
gpt4 key购买 nike

如果缺少 javascript 或 css 文件,是否有可能抛出异常?

我尝试过下面的代码,但它从未抛出异常......

    public class BundleConfig {
public static void RegisterBundles(BundleCollection bundles) {
....

bundles.Add(new ScriptBundle("~/bundles/something").Include("~/Scripts/nonExistingFile.js"));
// I would like the above usage of Include method with
// a non-existing file to throw an exception to make it
// obvious that an expected file is missing ...
// but since it does not I tried to implement a method as below ...
...
AssertThatAllFilesExist(bundles);
// but unfortunately an exception is never thrown but when
// iterating the files in the method below,
// the non-existing file seems to never become retrieved ...
}

private static void AssertThatAllFilesExist(BundleCollection bundles) {
HttpContext currentHttpContext = HttpContext.Current;
var httpContext = new HttpContextWrapper(currentHttpContext);
foreach (var bundle in bundles) {
var bundleContext = new BundleContext(httpContext, bundles, bundle.Path);
IEnumerable<FileInfo> files = bundle.EnumerateFiles(bundleContext);
foreach (var file in files) {
if (!file.Exists) {
// if this problem would occur then it should
// indicate that one of the arguments of the
// method "Bundle.Include" does not
// correspond to an existing file ...
throw new ArgumentException("The following file does not exist: " + file.FullName);
}
}
}
}
}

最佳答案

我使用此类而不是ScriptBundle:

public class ScriptBundleWithException : ScriptBundle
{
public ScriptBundleWithException( string virtualPath ) : base( virtualPath ) {}
public ScriptBundleWithException( string virtualPath, string cdnPath ) : base( virtualPath, cdnPath ) {}

public override Bundle Include( params string[] virtualPaths )
{
foreach ( var virtualPath in virtualPaths ) {
Include( virtualPath );
}
return this;
}

public override Bundle Include( string virtualPath, params IItemTransform[] transforms )
{
var realPath = System.Web.Hosting.HostingEnvironment.MapPath( virtualPath );
if ( !File.Exists( realPath ) ) {
throw new FileNotFoundException( "Virtual path not found: " + virtualPath );
}
return base.Include( virtualPath, transforms );
}
}

然后在配置中:

bundles.Add( new ScriptBundleWithException( "~/bundles/something" ) //...

关于asp.net-mvc - 方法 "Bundle.Include"(在与 ASP.NET MVC 一起使用的 System.Web.Optimization 中)是否可以抛出异常而不是默默地忽略丢失的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14531934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com