如何以编程方式清除控制器操作方法的outputcache

mar*_*l_g 62 asp.net asp.net-mvc

如果控制器操作在操作上指定了OutputCache属性,是否有任何方法可以清除输出缓存而无需重新启动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 );
}
Run Code Online (Sandbox Code Playgroud)

我正在考虑使用HttpResponse.RemoveOutputCacheItem(string path)它来清除它,但是我很难弄清楚应该将它映射到action方法的路径.我将再次尝试使用ViewName呈现的aspx页面.

也许我只是手动插入的输出RenderToStringHttpContext.Cache,而是如果我不明白这一个.

更新

请注意,OutputCache是​​VaryByParam,测试出硬编码路径"/ controller/action"实际上并没有清除outputcache,所以看起来它必须匹配"/ controller/action/param1/param2".

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

eu-*_*-ne 53

试试这个

var urlToRemove = Url.Action("AjaxHtmlOutputMethod", "Controller");
HttpResponse.RemoveOutputCacheItem(urlToRemove);
Run Code Online (Sandbox Code Playgroud)

更新:

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);
Run Code Online (Sandbox Code Playgroud)

更新:

试试这个:

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

否则缓存删除将无效,因为您已在用户的计算机上缓存HTML输出

  • 只是一张纸条.在MVC3中,您现在需要使用`Location = OutputCacheLocation.Server`并包含`System.Web.UI`.`'Location ="Server"`将不再编译. (9认同)
  • 我想我回答了自己的问题:http://stackoverflow.com/questions/11585/clearing-page-cache-in-asp-net/2876701#2876701 (2认同)

小智 6

继接受的答案,支持VaryByParam参数:

  [OutputCache (Duration=3600, VaryByParam="param1;param2", Location = OutputCacheLocation.Server)]
  public string AjaxHtmlOutputMethod(string param1, string param2)
  {
       object routeValues = new { param1 = param1, param2 = param2 };

       string url = Url.Action("AjaxHtmlOutputMethod", "Controller", routeValues);

       Response.RemoveOutputCacheItem(url);
  }
Run Code Online (Sandbox Code Playgroud)

然而,Egor的答案要好得多,因为它支持所有OutputCacheLocation值:

  [OutputCache (Duration=3600, VaryByParam="param1;param2")]
  public string AjaxHtmlOutputMethod(string param1, string param2)
  {
       if (error)
       {
           Response.Cache.SetNoStore(); 
           Response.Cache.SetNoServerCaching();
       }
  }
Run Code Online (Sandbox Code Playgroud)

SetNoStore()SetNoServerCaching()被调用时,它们阻止了当前请求被缓存.除非为这些请求调用函数,否则将缓存更多请求.

这是处理错误情况的理想选择 - 通常您希望缓存响应,但不包含错误消息.


小智 5

I think correct flow is:

filterContext.HttpContext.Response.Cache.SetNoStore()
Run Code Online (Sandbox Code Playgroud)