ASP.NET MVC 输出缓存属性:如果设置了参数不缓存?
-
19-09-2019 - |
题
我有以下行动:
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) { /* ... */ }
}
但这看起来很难看。
你会如何实施这个?
解决方案
我认为你所拥有的可能是最干净的选择。
另一个选项(我尚未测试过)可能是设置 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
不隶属于 StackOverflow