如果param是列表,则VaryByParam失败

时间:2014-07-21 08:29:08

标签: asp.net-mvc-5 outputcache varybyparam

我在MVC中有这个动作

[OutputCache(Duration = 1200, VaryByParam = "*")]
public ActionResult FilterArea( string listType, List<int> designersID, int currPage = 1 )
{
   // Code removed
}

无法使用类似

的网址显示正确的HTML

这是.NET中OutputCache的已知错误导致无法使用列表参数识别VaryByParam还是我遗漏了某些内容?

1 个答案:

答案 0 :(得分:1)

我在MVC3中也有同样的问题,我相信它在MVC5中的情况仍然相同。

这是我的设置。

请求

POST,Content-Type:application / json,传入一个字符串数组作为参数

{ "options": ["option1", "option2"] }

控制器方法

[OutputCache(Duration = 3600, Location = OutputCacheLocation.Any, VaryByParam = "options")]
public ActionResult GetOptionValues(List<string> options)

我尝试了使用OutputCache的所有选项,但它并没有为我提供缓存。绑定工作正常,实际工作方法。我最大的怀疑是OutputCache没有创建唯一的缓存键,所以我甚至从System.Web.MVC.OutputCache中取出代码进行验证。我已经确认即使传入List<string>也能正确构建唯一键。还有其他错误,但不值得花费更多精力。

OutputCacheAttribute.GetUniqueIdFromActionParameters(filterContext,
                OutputCacheAttribute.SplitVaryByParam(this.VaryByParam);

解决方法

我最后在另一个SO帖子之后创建了我自己的OutputCache属性。更容易使用,我可以享受一天剩下的时间。

控制器方法

[MyOutputCache(Duration=3600)]
public ActionResult GetOptionValues(Options options)

自定义请求类

我已从List<string>继承,因此我可以调用MyOutputcache类中的重写.ToString()方法,为我提供唯一的缓存键字符串。仅这种方法就解决了其他问题,但不适用于我。

[DataContract(Name = "Options", Namespace = "")]
public class Options: List<string>
{
    public override string ToString()
    {
        var optionsString= new StringBuilder();
        foreach (var option in this)
        {
            optionsString.Append(option);
        }
        return optionsString.ToString();
    }
}

自定义OutputCache类

public class MyOutputCache : ActionFilterAttribute
{
    private string _cachedKey;

    public int Duration { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.Url != null)
        {
            var path = filterContext.HttpContext.Request.Url.PathAndQuery;
            var attributeNames = filterContext.ActionParameters["Options"] as AttributeNames;
            if (attributeNames != null) _cachedKey = "MYOUTPUTCACHE:" + path + attributeNames;
        }
        if (filterContext.HttpContext.Cache[_cachedKey] != null)
        {
            filterContext.Result = (ActionResult) filterContext.HttpContext.Cache[_cachedKey];
        }
        else
        {
            base.OnActionExecuting(filterContext);
        }
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.HttpContext.Cache.Add(_cachedKey, filterContext.Result, null,
            DateTime.Now.AddSeconds(Duration), System.Web.Caching.Cache.NoSlidingExpiration,
            System.Web.Caching.CacheItemPriority.Default, null);
        base.OnActionExecuted(filterContext);
    }
}