ASP.NET MVC OutputCacheAttribute: don't cache if option is set?

I have the following action:

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

I would like to [OutputCache]perform this action, but I would like to:

  • he does not use cache if id == null; or
  • it uses cache if id == null, but with a different duration.

I think I can achieve this:

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

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

However, this solution implies 2 actions, when idin fact it is optional, therefore it can lead to repeated repetition of the code. Of course, I could do something like

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) { /* ... */ }
}

but it seems ugly.

How do you implement this?

+3
source share
1 answer

, , , .

, , , VaryByCustom GetVaryByCustomString Global.asax.

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

+3

Source: https://habr.com/ru/post/1727476/


All Articles