我正在尝试迭代已添加到特定捆绑包的文件列表。
例如,如果我有一个像这样创建的捆绑包:
'_App_Start.vbhtml:
BundleConfig.RegisterBundles(System.Web.Optimization.BundleTable.Bundles)
'BundleConfig.vb:
Imports System.Web.Optimization
Public Class BundleConfig
Public Shared Sub RegisterBundles(ByRef bundles As BundleCollection)
bundles.Add(New ScriptBundle("~/bundles/example").Include(
"~/Scripts/file1.js",
"~/Scripts/file2.js"
))
End Sub
End Class
从项目中的其他 *.vbhtml 文件中,我希望能够迭代一个捆绑包,在本例中为"~/bundles/example",以便在此示例中获取文件列表"~/Scripts/file1.js"和"~/Scripts/file2.js"。
这是我到目前为止所拥有的:
Dim myBundle As System.Web.Optimization.Bundle
myBundle = BundleTable.Bundles.GetBundleFor("~/bundles/example")
'== Stuck Here:
Dim myContext As BundleContext
myContext = "** Pleae Help **"
Dim myIEnumerable As IEnumerable(Of BundleFile)
myIEnumerable = myBundle.EnumerateFiles(myContext)
查看 Bundle.EnumerateFiles 方法的文档 (https://msdn.microsoft.com/en-us/library/system.web.optimization.bundle.enumeratefiles(v=vs.110(.aspx( 我看到第一个参数是"BundleContext"。
这就是我被困住的地方!如何或在哪里获取要传递给枚举文件方法的捆绑上下文值?
编辑 - 使用哲也答案中提供的代码的完整工作示例
Dim myBundle As System.Web.Optimization.Bundle
myBundle = BundleTable.Bundles.GetBundleFor("~/bundles/example")
Dim currentContext As HttpContext = httpContext.Current
Dim httpCtxt As HttpContextWrapper
httpCtxt = New HttpContextWrapper(currentContext)
Dim myContext As BundleContext
myContext = New BundleContext(httpCtxt, BundleTable.Bundles, "~/bundles/example")
Dim myIEnumerable As IEnumerable(Of BundleFile)
myIEnumerable = myBundle.EnumerateFiles(myContext)
Dim filepath As String
For Each bundlefile In myIEnumerable.ToArray
filepath = bundlefile.IncludedVirtualPath
' do stuff ..
Next
根据 MSDN 文档,BundleContext
是一个类,其构造函数接受 3 个参数,如下所示:
Public Class BundleContext
Public Sub New (context As HttpContextBase, collection As BundleCollection, bundleVirtualPath As String)
End Class
因此,您需要传递 HttpContext
、 BundleTable.Bundles
(这是默认BundleCollection
,如果有,请更改为自定义捆绑包集合(和捆绑包虚拟路径来创建BundleContext
实例,如以下示例所示:
Dim currentContext As HttpContext = HttpContext.Current
Dim contextWrapper As HttpContextWrapper
contextWrapper = New HttpContextWrapper(currentContext)
Dim myContext As BundleContext
myContext = New BundleContext(contextWrapper, BundleTable.Bundles, "~/bundles/example")