如何以编程方式清除控制器操作方法的输出缓存

如何以编程方式清除控制器操作方法的输出缓存

问题描述:

如果控制器动作在动作上指定了 OutputCache 属性,有没有什么方法可以清除输出缓存而无需重新启动 IIS?

If the controller action has the OutputCache attribute specified on an action, is there any way to clear the output cache without having to restart IIS?

[OutputCache (Duration=3600,VaryByParam="param1;param2")]
public string AjaxHtmlOutputMethod(string param1, string param2)
{
  var someModel = SomeModel.Find( param1, param2 );

  //set up ViewData
  ...

  return RenderToString( "ViewName", someModel );
}

我正在考虑使用 HttpResponse.RemoveOutputCacheItem(string path) 来清除它,但我无法弄清楚将它映射到操作方法的路径应该是什么.我打算用 ViewName 渲染的 aspx 页面再试一次.

I'm looking at using HttpResponse.RemoveOutputCacheItem(string path) to clear it, but I'm having trouble figuring out what the path should be to map it to the action method. I'm going to try again with the aspx page that is rendered by ViewName.

如果我无法解决这个问题,我可能会手动将 RenderToString 的输出插入到 HttpContext.Cache 中.

Possibly I'll just manually insert the output of RenderToString into the HttpContext.Cache instead if I can't figure this one out.

更新

请注意,OutputCache 是 VaryByParam,并且测试硬编码路径/controller/action"实际上并不会清除 outputcache,因此它看起来必须匹配/controller/action/param1/param2".

Please note that the OutputCache is VaryByParam, and testing out a hardcoded path "/controller/action" does not actually clear the outputcache, so it looks like it has to match "/controller/action/param1/param2".

这意味着我可能不得不恢复到对象级缓存并手动缓存 RenderToString() 的输出:(

That means I'll probably have to revert to object level caching and manually cache the output for RenderToString() :(

试试这个

var urlToRemove = Url.Action("AjaxHtmlOutputMethod", "Controller");
HttpResponse.RemoveOutputCacheItem(urlToRemove);

更新:

var requestContext = new System.Web.Routing.RequestContext(
    new HttpContextWrapper(System.Web.HttpContext.Current),
    new System.Web.Routing.RouteData());

var Url = new System.Web.Mvc.UrlHelper(requestContext);

更新:

试试这个:

[OutputCache(Location= System.Web.UI.OutputCacheLocation.Server, Duration=3600,VaryByParam="param1;param2")]

否则缓存删除将不起作用,因为您已经在用户机器上缓存 HTML 输出

Otherwise the cache deletion won't work because you've cached the HTML output on the user's machine