这就是我在我的网站上所做的:
- 在 IIS 上使用 ASP.NET 应用程序池设置网站
- 将绑定主机设置为
your.domain.com
- 注意:不能使用
domain.com,否则子域将不会是无cookie的
- 在网站上创建一个名为
Static 的文件夹
- 设置另一个网站,将其指向之前创建的
Static 文件夹。
- 将绑定主机设置为
static.domain.com
- 使用包含非托管代码的应用程序池
- 在设置中打开会话状态并检查
Not enabled。
现在您有了一个静态网站。要设置打开Static文件夹下的web.config文件并替换为这个:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<sessionState mode="Off" />
<pages enableSessionState="false" validateRequest="false" />
<roleManager>
<providers>
<remove name="AspNetWindowsTokenRoleProvider" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
</staticContent>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
这会将文件缓存 30 天,删除 RoleManager(我不知道它是否会改变任何东西,但我删除了所有我能找到的),并从响应标头中删除一个项目。
但是这里有个问题,即使部署了新版本,你的内容也会被缓存,所以为了避免这种情况,我为 MVC 制作了一个辅助方法。基本上,您必须附加一些 QueryString,每次更改这些文件时都会更改。
default.css?v=1 ?v=2 ...
我的 MVC 方法获取最后写入日期并附加到文件 url:
public static string GetContent(this UrlHelper url, string link)
{
link = link.ToLower();
// last write date ticks to hex
var cacheBreaker = Convert.ToString(File.GetLastWriteTimeUtc(url.RequestContext.HttpContext.Request.MapPath(link)).Ticks, 16);
// static folder is in the website folders, but instead of
// www.domain.com/static/default.css I convert to
// static.domain.com/default.css
if (link.StartsWith("~/static", StringComparison.InvariantCultureIgnoreCase))
{
var host = url.RequestContext.HttpContext.Request.Url.Host;
host = String.Format("static.{0}", host.Substring(host.IndexOf('.') + 1));
link = String.Format("http://{0}/{1}", host, link.Substring(9));
// returns the file URL in static domain
return String.Format("{0}?v={1}", link, cacheBreaker);
}
// returns file url in normal domain
return String.Format("{0}?v={1}", url.Content(link), cacheBreaker);
}
并使用它(MVC3 Razor):
<link href="@Url.GetContent("~/static/default.css")" rel="stylesheet" type="text/css" />
如果您使用的是其他类型的应用程序,您也可以这样做,请创建一个在页面上附加 HtmlLink 的方法。