Asp.net Mvc中OutputCache緩存Bug
廣告:
Asp.net Mvc中設(shè)置OutputCache緩存Bug
[OutputCache(Duration =7500, VaryByParam = "none", VaryByCustom = "Crawler")]
public ActionResult Index()
{
Response.Cache.SetOmitVaryStar(true); ////
}
問題:以上設(shè)置為兩個小時間的緩存后,當(dāng)?shù)谝淮握埱笫怯墒謾C(jī)瀏覽器(老式手機(jī))以WAP方式觸發(fā)請求這個頁面的話,網(wǎng)站頁面在正常瀏覽器中變成下載頁面了。這種問題是偶爾會發(fā)生,機(jī)率不大。但是總會遇到。(Request headers中包含"Accept:text/vnd.wap.wml" Content-Type 類型為: text/vnd.wap.wml;charset=gb2312)。
問題的原因就在這里,正確的Content-Type應(yīng)該是"text/html; charset=gb2312"
解決方法:
1. 在Global.asax中,在Application_BeginRequest方法中,添加如下的代碼:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string acceptTypes = Request.Headers["Accept"];
if (!string.IsNullOrEmpty(acceptTypes) && acceptTypes.ToLower().IndexOf("text/vnd.wap.wml") > -1)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
}
2.更改服務(wù)器設(shè)置
前提條件:當(dāng)前Web服務(wù)器上沒有WAP站點(diǎn)
優(yōu)點(diǎn):一處更改,對當(dāng)前Web服務(wù)器上的所有站點(diǎn)都有效。
操作步驟:
進(jìn)入C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\Browsers
將Default.browser文件復(fù)制到桌面(另外再復(fù)制一份到另外一個文件夾進(jìn)行備份)
用你喜歡的編輯打開桌面上的Default.browser文件,找到<defaultBrowser id="Wml" parentID="Default" >部分,注釋或者刪除以下配置并保存:
<capabilities>
<capability name="preferredRenderingMime" value="text/vnd.wap.wml"/>
<capability name="preferredRenderingType" value="wml11"/>
</capabilities>
將修改過的Default.browser文件復(fù)制至"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\Browsers",覆蓋同名文件。
以管理員身份運(yùn)行命令行,cd進(jìn)入"C:\Windows\Microsoft.NET\Framework\v4.0.30319",運(yùn)行命令"aspnet_regbrowsers -i":
3.In the Global.asax (or Global.asax.cs) override the method GetVaryByCustomString with something similar like:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
if(custom.Equals("PreferredRenderingMime", StringComparison.InvariantCultureIgnoreCase))
{
try
{
if(String.IsNullOrEmpty(context.Request.Browser.PreferredRenderingMime))
return "text/html";
else
return context.Request.Browser.PreferredRenderingMime;
}
catch
{
return "text/html";
}
}
else
return base.GetVaryByCustomString(context, custom);
}
Then in <%@ OutputCache %> directive instead of VaryByHeader=”Content-Type” or VaryByHeader=”Accept” use VaryByCustom=”PreferredRenderingMime”.
網(wǎng)上流傳的設(shè)置:VaryByHeader="Content-Type",這個方法沒有試過。按原理加上的話,在緩存上面可能有一定的風(fēng)險,因?yàn)榭蛻舳耸嵌喾N多樣的。
廣告: