Asp.net mvc ASP.NET MVC OutputCacheAttribute:如果设置了参数,是否不缓存?
我有以下行动:Asp.net mvc ASP.NET MVC OutputCacheAttribute:如果设置了参数,是否不缓存?,asp.net-mvc,caching,outputcache,Asp.net Mvc,Caching,Outputcache,我有以下行动: public class HomeController : Controller { public ActionResult Index(int? id) { /* ... */ } } 我希望[OutputCache]执行该操作,但我希望: 如果id==null,则不使用缓存;或 如果id==null,则使用缓存,但持续时间不同 我认为我可以通过以下方式实现这一目标: public class HomeController : Controller { [
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) { /* ... */ }
}
但是,当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) { /* ... */ }
}
但这看起来很难看
您将如何实现这一点?我认为您拥有的可能是最干净的选择 另一个选项(我没有测试过)可能是设置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);
}
有关更多信息,请参见此处:不确定为什么投票被否决,因此+1。