gpt4 book ai didi

asp.net-mvc-5 - 如果参数是列表,则 VaryByParam 失败

转载 作者:行者123 更新时间:2023-12-01 23:30:09 25 4
gpt4 key购买 nike

我在 MVC 中执行了此操作

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

无法呈现正确的 HTML,其 url 如下

这是 .NET 中 OutputCache 的已知错误,因为无法识别带有列表参数的 VaryByParam 还是我遗漏了某些内容?

最佳答案

我在 MVC3 中也遇到了同样的问题,并且我相信在 MVC5 中仍然是同样的情况。

这是我的设置。

请求

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

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

Controller 方法

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

我尝试了 OutputCache 的所有可能选项,但它只是没有为我缓存。对于实际方法来说,绑定(bind)效果很好。我最大的怀疑是 OutputCache 没有创建唯一的缓存键,所以我什至从 System.Web.MVC.OutputCache 中提取了它的代码。核实。我已经验证它可以正确构建唯一的 key ,即使 List<string>被传入。那里还有其他东西有问题,但不值得花费更多精力。

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

解决方法

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

Controller 方法

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

自定义请求类

我继承自 List<string>所以我可以调用覆盖 .ToString() MyOutputcache 类中的方法给我一个唯一的缓存键字符串。仅此方法就解决了其他人的类似问题,但没有解决我的问题。

[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);
}
}

关于asp.net-mvc-5 - 如果参数是列表,则 VaryByParam 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24860685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com