基于Asp.net MVC中的Url参数进行缓存

时间:2011-05-20 12:25:25

标签: caching asp.net-mvc-3 asp.net-mvc-routing

我已经定义了一个路由文化/ Controller / action / id ...我的控制器包含以下操作..

 [OutputCache(Duration=60*10)]
        public ActionResult Index()
        {*/do magic here/*}

是否可以根据文化缓存内容?

1 个答案:

答案 0 :(得分:4)

localization complete guide提供了如何使用VaryByCustom参数实现此目的的示例。在global.asax中,您将覆盖GetVaryByCustomString方法:

public override string GetVaryByCustomString(HttpContext context, string value)
{
    if (value == "lang")
    {
        return Thread.CurrentThread.CurrentUICulture.Name;
    }
    return base.GetVaryByCustomString(context, value);
}

然后:

[OutputCache(Duration = 60 * 10, VaryByParam = "none", VaryByCustom = "lang")]
public ActionResult Index()
{
    /* do magic here */
    ...
}

或者,如果您只想依赖文化路线数据参数,您可以这样做:

public override string GetVaryByCustomString(HttpContext context, string value)
{
    if (value == "lang")
    {
        var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context));
        var culture = (string)routeData.Values["culture"];
        if (!string.IsNullOrEmpty(culture))
        {
            return culture;
        }
    }
    return base.GetVaryByCustomString(context, value);
}