1:減少靜態頁面請求
要讓靜態頁面支持這個需求,我們需要用到http頭中的Cache-Control: max-age。值得注意的是Cache-Control是在HTTP/1.1協議下的標識,它是HTTP/1.0協議中的Expires的升級。為了讓靜態頁支持Cache-Control,一種方案是在IIS中進行設置,如下,我在需要靜態緩存的頁面或者文件夾上右鍵->屬性:
可以看到其得到的http頭中已經有了Cache-Control: max-age=60這一項。
現在,我需要在1分鐘內反復請求該靜態頁,請求的行為我們分別通過下面幾種方式來實現,
F5代表瀏覽器的一次刷新,它對Last-Modified有效,但是對Cache-Control無效
點擊“轉到”或者光標移入地址欄然后回車對Cache-Control有效
CTRL+F5強制刷新,返回所有正文
我們通過HttpWatch得到的結果如下:
</staticContent>
</system.webServer>
復制代碼 代碼如下:
<location path="test2.htm">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache"/>
</staticContent>
</system.webServer>
</location>
復制代碼 代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
//處理點擊“轉到”或者光標移入地址欄然后回車,也就是本文所闡述的
this.Response.AddHeader("Cache-Control", "max-age=60");
//真是用來處理F5刷新的,也就是對Last-Modified有效
this.Response.AddHeader("Last-Modified", DateTime.Now.ToString("U", DateTimeFormatInfo.InvariantInfo));
DateTime IfModifiedSince;
if (DateTime.TryParse(this.Request.Headers.Get("If-Modified-Since"), out IfModifiedSince))
{
if ((DateTime.Now - IfModifiedSince.AddHours(8)).Seconds < 60)
{
Response.Status = "304 Not Modified";
Response.StatusCode = 304;
return;
}
}
}
結果如下:
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
復制代碼 代碼如下:
<%@ OutputCache CacheProfile="cache1" %>
新聞熱點
疑難解答
圖片精選