【问题标题】:OutputCache attribute and VaryByCustom without parameterOutputCache 属性和不带参数的 VaryByCustom
【发布时间】:2014-12-02 16:10:11
【问题描述】:

我正在尝试根据用户选择的语言使用 OutputCache 属性来缓存页面。

[OutputCache(Duration = 86400, Location = OutputCacheLocation.Client, VaryByParam = "", VaryByCustom = "lang")]
public ActionResult MyActionMethod()
{
    ...
}

当我们在页面上并且我们更改语言时它工作正常,酷!

但问题是:当用户第一次调用页面时,没有“lang”参数。所以缓存会在没有参数的情况下创建,如果我们更改语言后它不会被替换。

如果没有参数,我该如何处理这种情况?

任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: asp.net-mvc outputcache


    【解决方案1】:

    你说没有“lang”参数,是说没有“lang”自定义?

    在 global.asax 你应该有这样的东西:

    public override string GetVaryByCustomString(HttpContext context, string custom)
    {
        if (custom == "lang")
        {
            string lang = null;
    
            if (Request.UserLanguages != null && Request.UserLanguages.Length > 0)
            {
                lang = Request.UserLanguages.First().Split(new char[] { ';' }).First();
            }
            else
            {
                // Default
                lang = "en-US";
            }
    
            return string.Format("lang={0}", lang.ToLower());
        }
    
        return base.GetVaryByCustomString(context, custom);
    }
    

    然后它将默认值为“en-US”,否则在这种情况下从浏览器获取它,或者使用 cookie 实现它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多