RemoveOutputCacheItem 仅适用于路由参数,不适用于查询字符串。所以你可以修改你的路由定义:
routes.MapRoute(
"Default",
"{controller}/{action}/{product_Id}",
new { controller = "Home", action = "Index" }
);
现在你可以使用 RemoveOutputCacheItem 方法了:
public ActionResult RemoveCache(Guid product_Id)
{
var url = Url.Action("ProductPreview", "Common", new { product_Id = product_Id });
// the url must look like this: /Common/ProductPreview/eeb2fe32-db58-4fc3-87c8-b47480fbe094
// for the RemoveOutputCacheItem method to work
HttpResponse.RemoveOutputCacheItem(url);
return RedirectToAction("Index");
}
更新:
这是我的测试用例:
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[OutputCache(Duration = 3600, VaryByParam = "product_id")]
public ActionResult ProductPreview(Guid product_id)
{
var model = string.Format(
"{0} - {1}",
product_id,
DateTime.Now.ToLongTimeString()
)
return PartialView("_Foo", model);
}
public ActionResult RemoveCache(Guid product_id)
{
var url = Url.Action(
"ProductPreview",
"Home",
new { product_id = product_id }
);
HttpResponse.RemoveOutputCacheItem(url);
return RedirectToAction("Index");
}
}
查看(~/Views/Home/Index.cshtml):
@{
var productId = Guid.NewGuid();
}
@Html.ActionLink("product 1", "ProductPreview", new { product_id = Guid.NewGuid() })
<br/>
@Html.ActionLink("product 2", "ProductPreview", new { product_id = productId })
<br/>
@Html.ActionLink("product 3", "ProductPreview", new { product_id = Guid.NewGuid() })
<br />
@Html.ActionLink(
"clear cache for the second product",
"RemoveCache",
new { product_id = productId }
)
部分视图(~/Views/Home/_Foo.cshtml):
@model string
@Model
在global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{product_id}",
new { controller = "Home", action = "Index", product_id = UrlParameter.Optional }
);
}
更新 2:
现在您已经显示了您的代码,您似乎正在使用Html.RenderAction 帮助程序,而ProductPreview 是一个子操作。子操作与普通视图不存储在同一个缓存中,HttpResponse.RemoveOutputCacheItem 帮助器根本不适用于缓存的子操作。如果您仔细查看我之前的示例,您会发现我使用标准链接来执行 ProductPreview 操作。
目前您尝试实现的目标在 ASP.NET MVC 3 中是不可能实现的。如果您想使用甜甜圈输出缓存,我建议您使用 following article。希望此功能将添加到 ASP.NET MVC 4 中。