[英]How to use OutputCache in PartialView Controllers in MVC 5, C#?
我有Controller與PartialViewResult
或JsonResult
返回類型。
我想用[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;
}
我該如何實施呢?
VaryByParam
的OutputCache
默認值為"*"
因此這將根據查詢字符串中的所有參數或帖子中的參數來更改緩存。
你的表單上有一個防偽標記( @Html.AntiForgeryToken()
),每當頁面呈現時都會獲得一個新值,導致輸出緩存認為它是一個變體。
將VaryByParam設置為“none”,包括您想要改變的道具列表,或者使用VaryByCustom
寫一些自定義變體
[OutputCache(Duration = 120, Location = OutputCacheLocation.Server, VaryByParam="none")]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.