我正在尝试为我的操作结果实现输出缓存。
在我的操作中,根据某些业务规则返回响应。在我的回复中,我发送错误代码。 如果有任何错误,我不想缓存响应。
在行动结果中跟随
class Response
{
public int ErrorCode { get; set; }
public string Message { get; set; }
}
[OutputCache(CacheProfile = "Test")]
public ActionResult Sample()
{
Response response = new Response();
return new JsonResult { Data = response, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
我希望仅在ErrorCode == 0时缓存Result。
我尝试重写OutputCache,但它无法正常工作
public class CustomOutputCacheAttribute : OutputCacheAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Result is JsonResult)
{
var result = (JsonResult)filterContext.Result;
BaseReponse response = result.Data as BaseReponse;
if (!response.IsSuccess)
{
filterContext.HttpContext.Response.Cache.SetNoStore();
}
base.OnActionExecuted(filterContext);
}
}
}
有没有其他方法或方法来实现这一目标。
由于
答案 0 :(得分:3)
您可以根据结果错误代码创建自己的自定义属性,忽略[OutputCache]
,如下所示:
[OutputCache(Duration=60, VaryByParam="none")]
[OutputCacheValidation]
public ActionResult Sample()
{
var r = new Response();
r.ErrorCode = 0;
return Json(r, JsonRequestBehavior.AllowGet);
}
public class OutputCacheValidationAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
base.OnResultExecuting(filterContext);
filterContext.HttpContext.Response.Cache.AddValidationCallback(ValidatioCallback, filterContext.Result);
}
private static void ValidatioCallback(HttpContext context, object data, ref HttpValidationStatus validationStatus)
{
var jsonResult = data as JsonResult;
if (jsonResult == null) return;
var response = jsonResult.Data as Response;
if (response == null) return;
if (response.ErrorCode != 0)
{
//ignore [OutputCache] for this request
validationStatus = HttpValidationStatus.IgnoreThisRequest;
context.Response.Cache.SetNoServerCaching();
context.Response.Cache.SetNoStore();
}
}
}