簡體   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