I have Controller with PartialViewResult
or JsonResult
return type.
I wanna cache it with [OutputCache]
, but it doesn't work at all and always the following Index
controller Thread.Sleep(5000);
runs!!!
[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;
}
How should I implement it?
The OutputCache
default value for VaryByParam
is "*"
so this will vary the cache by all parameters in the query string or parameters in the post.
You have an anti-forgery token (@Html.AntiForgeryToken()
) on your form that gets a new value whenever the page is rendered, causing the output cache think it's a variation.
Either set VaryByParam to "none", include a list of props you do want to vary by, or write some custom variation with VaryByCustom
[OutputCache(Duration = 120, Location = OutputCacheLocation.Server, VaryByParam="none")]