Asp.net Mvc中OutputCache缓存Bug
广告:
Asp.net Mvc中设置OutputCache缓存Bug
[OutputCache(Duration =7500, VaryByParam = "none", VaryByCustom = "Crawler")]
public ActionResult Index()
{
Response.Cache.SetOmitVaryStar(true); ////
}
问题:以上设置为两个小时间的缓存后,当第一次请求是由手机浏览器(老式手机)以WAP方式触发请求这个页面的话,网站页面在正常浏览器中变成下载页面了。这种问题是偶尔会发生,机率不大。但是总会遇到。(Request headers中包含"Accept:text/vnd.wap.wml" Content-Type 类型为: text/vnd.wap.wml;charset=gb2312)。
问题的原因就在这里,正确的Content-Type应该是"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.更改服务器设置
前提条件:当前Web服务器上没有WAP站点
优点:一处更改,对当前Web服务器上的所有站点都有效。
操作步骤:
进入C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\Browsers
将Default.browser文件复制到桌面(另外再复制一份到另外一个文件夹进行备份)
用你喜欢的编辑打开桌面上的Default.browser文件,找到<defaultBrowser id="Wml" parentID="Default" >部分,注释或者删除以下配置并保存:
<capabilities>
<capability name="preferredRenderingMime" value="text/vnd.wap.wml"/>
<capability name="preferredRenderingType" value="wml11"/>
</capabilities>
将修改过的Default.browser文件复制至"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\Browsers",覆盖同名文件。
以管理员身份运行命令行,cd进入"C:\Windows\Microsoft.NET\Framework\v4.0.30319",运行命令"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”.
网上流传的设置:VaryByHeader="Content-Type",这个方法没有试过。按原理加上的话,在缓存上面可能有一定的风险,因为客户端是多种多样的。
广告: