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

Moh*_*yan 3 c# asp.net-mvc outputcache

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

我该如何实施呢?

Sho*_*hoe 8

OutputCache默认值VaryByParam"*"这样,这将通过在后的查询字符串或参数的所有参数改变缓存.

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

将VaryByParam设置为"none",包括您想要改变的道具列表,或者写一些自定义变体 VaryByCustom

[OutputCache(Duration = 120, Location = OutputCacheLocation.Server, VaryByParam="none")]
Run Code Online (Sandbox Code Playgroud)