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

时间:2015-04-11 06:05:03

标签: c# asp.net-mvc outputcache

我的控制器有PartialViewResultJsonResult返回类型 我想用[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;
}

我该如何实施?

1 个答案:

答案 0 :(得分:8)

OutputCache的{​​{1}}默认值为VaryByParam,因此会根据查询字符串中的所有参数或帖子中的参数来更改缓存。

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

将VaryByParam设置为&#34;无&#34;,包含您想要改变的道具列表,或者使用@Html.AntiForgeryToken()

写一些自定义变体
VaryByCustom