【发布时间】:2016-11-08 02:42:24
【问题描述】:
我正在尝试解决浏览器缓存的问题。每当 js 和 css 文件有任何更改时,这些文件都是从浏览器缓存而不是服务器提供的,我在互联网上进行了研究,发现 this great post 来自 mads krinstinsen。
我在App_Code 文件夹中的一个类中包含了以下类和方法。
using System;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Web.Hosting;
public class Fingerprint
{
public static string Tag(string rootRelativePath)
{
if (HttpRuntime.Cache[rootRelativePath] == null)
{
string absolute = HostingEnvironment.MapPath("~" + rootRelativePath);
DateTime date = File.GetLastWriteTime(absolute);
int index = rootRelativePath.LastIndexOf('/');
string result = rootRelativePath.Insert(index, "/v-" + date.Ticks);
HttpRuntime.Cache.Insert(rootRelativePath, result, new CacheDependency(absolute));
}
return HttpRuntime.Cache[rootRelativePath] as string;
}
}
后来我更改了我所有 aspx 页面(近 500 个位置)中的引用,如下所示。
<script type="text/javascript" src="<%=Fingerprint.Tag("/Scripts/JQuery/jquery.color.js")%>"></script>
<script type="text/javascript" src="<%=Fingerprint.Tag("/Scripts/JQuery/jquery.glowbuttons.js?v=1.1")%>"></script>
按照建议,我还添加了以下重写规则并在 IIS 中安装了重写模块。
<rewrite>
<rules>
<rule name="fingerprint">
<match url="([\S]+)(/v-[0-9]+/)([\S]+)" />
<action type="Rewrite" url="{R:1}/{R:3}" />
</rule>
</rules>
</rewrite>
现在我面临的问题
这一切都在我的开发环境中发挥了作用。当我将代码发布到 iis(uat 和我的本地 iis)时,相同的代码不起作用。
Fingerprint.Tag() 方法返回错误的 URL。
我的开发网址如下所示
http://localhost:54992/login.aspx
我的 IIS 网站 URL 如下所示
http://www.example.com/myClientName/login.aspx
您可能已经注意到 IIS 上的额外级别的 url 段 (\myClientName\),这就是导致问题的原因。
我还添加了在 URL 中添加 myClientName 部分的逻辑,不幸的是这也不起作用。
在 IIS 托管网站上,由于 url 路径跳过了 myClientName 部分,因此出现了大量 404 错误。
更新 1
我还尝试了以下另一个版本的相同方法,它检查代码是在 iisexpress 还是在完整 IIS 上运行并相应地生成路径
public static string Tag(string rootRelativePath)
{
if (rootRelativePath.Contains("~"))
rootRelativePath = rootRelativePath.Replace("~", string.Empty);
bool isRunningInIisExpress = Process.GetCurrentProcess()
.ProcessName.ToLower().Contains("iisexpress");
if (HttpRuntime.Cache[rootRelativePath] == null)
{
string siteAlias = string.Empty;
if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["SiteName"]))
siteAlias = WebConfigurationManager.AppSettings["SiteName"].ToString();
string absolute = HostingEnvironment.MapPath("~" + rootRelativePath);
DateTime date = File.GetLastWriteTime(absolute);
int index = rootRelativePath.LastIndexOf('/');
string result = rootRelativePath.Insert(index, "/v-" + date.Ticks);
if (!isRunningInIisExpress)
{
siteAlias = "/" + siteAlias;
result = siteAlias + result;
}
if (File.Exists(absolute))
HttpRuntime.Cache.Insert(rootRelativePath, result, new CacheDependency(absolute));
}
return HttpRuntime.Cache[rootRelativePath] as string;
}
请指引我正确的方向。
【问题讨论】:
-
如果你改写规则会发生什么?直播中的开发路径会一样吗?
-
@Dexion 你的意思是像
-
是的。我建议也比较 iis/站点配置。
-
这个重写规则是第一次在config.both中引入,开发配置文件和iis配置文件的重写规则是一样的,要不要修改?我不太了解重写规则约定
-
删除 dev 和 live 上的规则并检查 url - 您需要确定规则或其他内容添加了额外的文件夹级别。
标签: c# asp.net url caching iis