【问题标题】:How to use OutputCache in PartialView Controllers in MVC 5, C#?如何在 MVC 5、C# 的 PartialView 控制器中使用 OutputCache?
【发布时间】:2015-04-11 06:05:03
【问题描述】:

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

我应该如何实现它?

【问题讨论】:

    标签: c# asp.net-mvc outputcache


    【解决方案1】:

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

    您的表单上有一个防伪令牌 (@Html.AntiForgeryToken()),每当呈现页面时,该令牌都会获取一个新值,从而导致输出缓存认为这是一个变体。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      相关资源
      最近更新 更多