背景:我正在使用HTML5脱机App并动态构建清单文件。基本上,清单文件需要列出页面将请求的每个静态文件。当文件实际上是静态的时,效果很好,但是我在System.Web.Optimization中使用捆绑和精简,所以我的文件不是静态的。
在调试符号加载时(即在VS中进行调试),则从MVC视图调用实际的物理文件。但是,在发布模式下,它调用一个虚拟文件,该文件看起来可能如下所示:/bundles/scripts/jquery?v=FVs3ACwOLIVInrAl5sdzR2jrCDmVOWFbZMY6g6Q0ulE1
所以我的问题:我怎样才能在代码中得到这个URL来将它添加到离线应用程序清单中呢?
我试过:
var paths = new List<string>()
{
"~/bundles/styles/common",
"~/bundles/styles/common1024",
"~/bundles/styles/common768",
"~/bundles/styles/common480",
"~/bundles/styles/frontend",
"~/bundles/scripts/jquery",
"~/bundles/scripts/common",
"~/bundles/scripts/frontend"
};
var bundleTable = BundleTable.Bundles;
foreach (var bundle in bundleTable.Where(b => paths.Contains(b.Path)))
{
var bundleContext = new BundleContext(this.HttpContext, bundleTable, bundle.Path);
IEnumerable<BundleFile> files = bundle.GenerateBundleResponse(bundleContext).Files;
foreach (var file in files)
{
var filePath = file.IncludedVirtualPath.TrimStart(new[] { '~' });
sb.AppendFormat(formatFullDomain, filePath);
}
} 以及用GenerateBundleResponse()代替EnumerateFiles(),但是它总是返回原始的文件路径。
我也愿意接受其他的实现建议。谢谢。
更新: (7/7/14 13:45)
除了下面的答案之外,我还添加了这个Bundles Registry,以保存所需的静态文件列表,以便它在所有浏览器中都能在调试模式下工作。(见下文评论)
public class Registry
{
public bool Debug = false;
public Registry()
{
SetDebug();
}
[Conditional("DEBUG")]
private void SetDebug()
{
Debug = true;
}
public IEnumerable<string> CommonScripts
{
get
{
if (Debug)
{
return new string[]{
"/scripts/common/jquery.validate.js",
"/scripts/common/jquery.validate.unobtrusive.js",
"/scripts/common/knockout-3.1.0.debug.js",
"/scripts/common/jquery.timepicker.js",
"/scripts/common/datepicker.js",
"/scripts/common/utils.js",
"/scripts/common/jquery.minicolors.js",
"/scripts/common/chosen.jquery.custom.js"
};
}
else
{
return new string[]{
"/scripts/common/commonbundle.js"
};
}
}
}
}我对这个解决方案一点也不满意。如果你能改进的话,请提出建议。
发布于 2014-07-07 09:51:49
我可以从这篇博客文章创建您自己的令牌中提出一个替代方案。
总之,作者建议使用网络要领来创建捆绑文件,然后创建一个剃刀助手来生成令牌,在本例中是基于上次更改的日期和时间。
public static class StaticFile
{
public static string Version(string rootRelativePath)
{
if (HttpRuntime.Cache[rootRelativePath] == null)
{
var absolutePath = HostingEnvironment.MapPath(rootRelativePath);
var lastChangedDateTime = File.GetLastWriteTime(absolutePath);
if (rootRelativePath.StartsWith("~"))
{
rootRelativePath = rootRelativePath.Substring(1);
}
var versionedUrl = rootRelativePath + "?v=" + lastChangedDateTime.Ticks;
HttpRuntime.Cache.Insert(rootRelativePath, versionedUrl, new CacheDependency(absolutePath));
}
return HttpRuntime.Cache[rootRelativePath] as string;
}
}然后你就可以像这样引用捆绑的文件。
@section scripts {
<script src="@StaticFile.Version("~/Scripts/app/myAppBundle.min.js")"></script>}那么你就可以控制这个令牌了,你可以用它做你想做的事。
https://stackoverflow.com/questions/24607165
复制相似问题