2010-01-06 29 views
3

我有以下作用:ASP.NET MVC OutputCacheAttribute:如果设置了参数,不要缓存?

public class HomeController : Controller 
{ 
    public ActionResult Index(int? id) { /* ... */ } 
} 

我想[OutputCache]这一行动,但我想,要么:

  • 它不使用高速缓存如果id == null;或
  • 它使用缓存如果id == null但具有不同的持续时间。

我想我可以做到这一点:

public class HomeController : Controller 
{ 
    [OutputCache(VaryByParam = "none", Duration = 3600)] 
    public ActionResult Index() { /* ... */ } 

    [OutputCache(VaryByParam = "id", Duration = 60)] 
    public ActionResult Index(int id) { /* ... */ } 
} 

但是这种解决方案意味着2个动作,当id实际上是可选的,所以这可能会产生一些代码重复。当然,我可以做类似

public class HomeController : Controller 
{ 
    [OutputCache(VaryByParam = "none", Duration = 3600)] 
    public ActionResult Index() { return IndexHelper(null); } 

    [OutputCache(VaryByParam = "id", Duration = 60)] 
    public ActionResult Index(int id) { return IndexHelper(id); } 

    private ActionResult IndexHelper(int? id) { /* ... */ } 
} 

但这看起来很丑。

你将如何实现这一点?

+1

不知道为什么,这是downvoted,所以+1。 – Gregory 2010-03-09 07:53:37

回答

3

我想你有什么可能是最干净的选择。

另一个选项,我没有测试过,可能是设置VaryByCustom参数并覆盖Global.asax中的GetVaryByCustomString。

public override string GetVaryByCustomString(HttpContext context, string arg) 
{ 
    if (arg.ToLower() == “id”) 
    { 
     // Extract and return value of id from query string, if present. 
    } 

    return base.GetVaryByCustomString(context, arg); 
} 

在这里看到更多的信息:http://codebetter.com/blogs/darrell.norton/archive/2004/05/04/12724.aspx