url.content的剃刀扩展方法以防止缓存 [英] razor extension method for url.content to prevent caching
问题描述
我想重写Url.Content,以将查询字符串参数附加到Url.Content上的结果字符串中.
I would like to override Url.Content to append a query string parameter to the resulting string on Url.Content.
原因是,我有一个要开发的Web应用程序,对于每个发行版,用户必须清除其缓存以获取新的CSS和JS.一种解决方案是在查询字符串后附加一个版本号,以强制加载新版本.
The reason being, I have a web application that I develop, and with each release, users must clear their cache to get the new css and js. A solution for this is to append a version number to the querystring to force loading of the new version.
可行的解决方案如下:
@{ var version = "?v=" + ViewBag.VersionNumber; }
<head>
<link href="@Url.Content("~/ux/css/base.css")@version" rel="stylesheet" type="text/css" />
</head>
版本是在配置文件中设置的,因此对于每个发行版,该版本都会更新.但我希望此方法更加自动化,因为当前每次添加新的CSS引用时,我们都必须记住将@version添加到字符串中.一个扩展方法,可以返回带有已附加版本号的路径,这是完美的.
Version is set in a config file so with each release, the version is updated. I would like this to be more automatic though, as currently any time a new css reference is added, we must remember to add @version to the string. An extension method the returns the path with the version number already appended would be perfect.
此外,如果有人知道我可以通过TFS签入或编译自动更改版本号,那将真的很有用.
Also, if anyone knows who I could make changing the version number automatic with TFS check-ins or compiles that would be really useful too.
推荐答案
您可以执行以下操作:
public static string VersionedContent(this UrlHelper urlHelper, string contentPath)
{
string result = urlHelper.Content(contentPath);
var versionService = Engine.IocService.GetInstance<IVersionService>();
string tag = versionService.GetVersionTag();
if (result.Contains('?'))
{
result += "&v="+tag;
}
else
{
result += "?v="+tag;
}
return result;
}
版本服务可能看起来像这样:
Version Service could look something like this:
public class VersionService : IVersionService
{
string _versionTag;
public VersionService()
{
_versionTag = Assembly.GetExecutingAssembly().GetName().Version.ToString();
_versionTag = _versionTag.Replace('.', '-');
}
#region IVersionedContentService Members
public string GetVersionTag()
{
return _versionTag;
}
#endregion
}
您可能想看看盒式磁带
*编辑* 对于自动化.使用TFS构建编号,请查看: automatic-assembly-file-版本号在tfs-2010
* EDIT * For autom. build numbers with TFS, check out: automatic-assembly-file-version-numbering-in-tfs-2010
这篇关于url.content的剃刀扩展方法以防止缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!