繁体   English   中英

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

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

我有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;
}

我该如何实施呢?

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

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

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

[OutputCache(Duration = 120, Location = OutputCacheLocation.Server, VaryByParam="none")]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM