gpt4 book ai didi

c# - 在 MVC3 中自定义输出缓存

转载 作者:行者123 更新时间:2023-11-30 22:25:58 24 4
gpt4 key购买 nike

我有一些 Controller 操作需要自定义缓存。例如,假设我有一个 Controller Action ActionResult Index(string name) {}。我想在服务器上缓存此操作的 HTML,除非 url 中有“live=true”查询字符串参数。如果存在该参数,我想从服务器缓存中删除该操作结果并正常提供响应。

我们通常使用 OutputCache(Location=OutputCacheLocation.Server) 属性来进行缓存。如果 URL 中存在 live=true 参数,是否可以以某种方式扩展此属性并清除缓存?

如果我不能自定义 OutputCache 属性来获得我需要的行为,是否有其他方法可以用来完成此操作?

更新

根据 James 的反馈,这里是我的代码:

public class LiveOutputCacheAttribute : OutputCacheAttribute
{
private const string _resetParam = "live";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var context = filterContext.HttpContext;
AddLiveToVaryByParam();
if (context.Request[_resetParam] == "true")
{
var urlToRemove = GetUrlToRemove(filterContext);
context.Response.RemoveOutputCacheItem(urlToRemove);
return;
}
base.OnActionExecuting(filterContext);
}

private void AddLiveToVaryByParam()
{
// add live reset flag when vary by param is specified
if (VaryByParam != "*" && !VaryByParam.Contains("live"))
VaryByParam = string.Format("{0};{1}",VaryByParam, _resetParam).TrimStart(';');
}

private static string GetUrlToRemove(ActionExecutingContext filterContext)
{
var routeValues = new RouteValueDictionary(filterContext.ActionParameters);
var urlHelper = new UrlHelper(filterContext.RequestContext);
string action = filterContext.ActionDescriptor.ActionName;
string controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
return urlHelper.Action(action, controller, routeValues);
}
}

以下是我如何在我的操作中使用它:

[LiveOutputCache(Location = OutputCacheLocation.Server, Duration = 60 * 60, VaryByParam = "name")]
public ActionResult Index(string name)
{
ViewData.Model = name + "-----" + DateTime.Now.Ticks.ToString();
return View();
}

问题是当我使用 live=true 参数时,它仍然没有从缓存中删除原始请求。我在这里做错了什么吗?

最佳答案

您可以使用 VaryByParam属性来检查实时选项是否为真,例如

public class LiveOutputCacheAttribute : OutputCacheAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (VaryByParam == "true")
{
// clear cache
return;
}

base.OnActionExecuting(filterContext);
}
}

...

[LiveOutputCache(Location=OutputCacheLocation.Server, VaryByParam="live")]
public ActionResult Index(string name)
{
...
}

参见 How to programmatically clear outputcache for controller action method对于它的清算部分。

关于c# - 在 MVC3 中自定义输出缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12091286/

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