Edg*_*gar 2 javascript asp.net-mvc
我正在和别人的代码一起工作,所以我不知道整个画面,我甚至不知道MVC那么好,但问题在于......
在Site.Master中有一个
<%= Html.IncludeJs("ProductPartial")%>
Run Code Online (Sandbox Code Playgroud)
在最终加价中产生这条线
<script type="text/javascript" src="/Scripts/release/ProductPartial.js"></script>
Run Code Online (Sandbox Code Playgroud)
我在JS文件中做了一些更改,但旧版本显然是由浏览器缓存的,因此在用户刷新之前不会显示更改.通常的解决方法是在脚本源路径的末尾添加一个版本标记,但我不知道在这种情况下如何做到这一点.
有什么建议?
为什么不编写自己的 Html helper 扩展方法,并使其输出应用程序程序集的版本号?沿着这些路线的东西应该可以解决问题:
public static MvcHtmlString IncludeVersionedJs(this HtmlHelper helper, string filename)
{
var version = Assembly.GetExecutingAssembly().GetName().Version;
return MvcHtmlString.Create(filename + "?v=" + version);
}
Run Code Online (Sandbox Code Playgroud)
然后,无论何时向用户发布新版本,您都可以增加程序集的版本号,并且他们的缓存将在整个应用程序中失效。
我通过将最后修改的时间戳作为脚本的查询参数来解决这个问题.
我用扩展方法做了这个,并在我的CSHTML文件中使用它. 注意:此实现将时间戳缓存1分钟,因此我们不会对磁盘进行过多的颠簸.
这是扩展方法:
public static class JavascriptExtension {
public static MvcHtmlString IncludeVersionedJs(this HtmlHelper helper, string filename) {
string version = GetVersion(helper, filename);
return MvcHtmlString.Create("<script type='text/javascript' src='" + filename + version + "'></script>");
}
private static string GetVersion(this HtmlHelper helper, string filename)
{
var context = helper.ViewContext.RequestContext.HttpContext;
if (context.Cache[filename] == null) {
var physicalPath = context.Server.MapPath(filename);
var version = "?v=" +
new System.IO.FileInfo(physicalPath).LastWriteTime
.ToString("yyyyMMddhhmmss");
context.Cache.Add(physicalPath, version, null,
DateTime.Now.AddMinutes(1), TimeSpan.Zero,
CacheItemPriority.Normal, null);
context.Cache[physicalPath] = version;
return version;
}
else {
return context.Cache[filename] as string;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在CSHTML页面中:
@Html.IncludeVersionedJs("/MyJavascriptFile.js")
Run Code Online (Sandbox Code Playgroud)
在呈现的HTML中,它显示为:
<script type='text/javascript' src='/MyJavascriptFile.ks?20111129120000'></script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5802 次 |
| 最近记录: |