如何在 MVC 5、C# 的 PartialView 控制器中使用 OutputCache?

How to use OutputCache in PartialView Controllers in MVC 5, C#?

我有 PartialViewResultJsonResult return 类型的控制器。
我想用 [OutputCache] 缓存它,但它根本不起作用,并且总是以下 Index 控制器 Thread.Sleep(5000); 运行!!!

[HttpPost]
[ValidateAntiForgeryToken]
[OutputCache(Duration = 120, Location = OutputCacheLocation.Server)]
public ActionResult Index(DevicesAjaxViewModel viewModel)
{
    try
    {
        //Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));
        //Response.Cache.SetCacheability(HttpCacheability.Server);
        Response.Cache.AddValidationCallback(IsCacheValid, Request.UserAgent);
#if DEBUG
        Thread.Sleep(5000);
#endif
        if (!ModelState.IsValid) return Json(new ModelError("Error in Model"));
        var allObjects = _objectService.GetAllObjects();
        string objectName = allObjects.First(q => q.Id == viewModel.ObjectId).Name;
        KeyValuePair<int, List<DeviceModel>> keyValuePair = ApplyFiltering(objectName, viewModel.PageNumber, false, viewModel.Filtering);
        FilteringDevicesResultModel filteringDevicesResultModel = new FilteringDevicesResultModel
        {
            Devices = keyValuePair.Value,
            FoundDevicesCount = keyValuePair.Key.ToMoneyFormat(),
            RequestId = viewModel.RequestId
        };

        return PartialView("~/Views/Partials/DevicesPagePartial.cshtml", filteringDevicesResultModel);
    }
    catch (Exception ex)
    {
        return Json(new ModelError(ex.Message));
    }
}

void IsCacheValid(HttpContext httpContext, object data, ref HttpValidationStatus status)
{
    if (true)
        status = HttpValidationStatus.Valid;
    else
        status = HttpValidationStatus.Invalid;
}

我该如何实施?

VaryByParamOutputCache 默认值为 "*" 因此这将根据查询字符串中的所有参数或 post 中的参数改变缓存。

您的表单上有一个防伪标记 (@Html.AntiForgeryToken()),每当页面呈现时它都会获得一个新值,导致输出缓存认为它是一个变体。

要么将 VaryByParam 设置为 "none",包括一个您确实希望改变的道具列表,或者使用 VaryByCustom

编写一些自定义变体
[OutputCache(Duration = 120, Location = OutputCacheLocation.Server, VaryByParam="none")]