【发布时间】:2015-02-18 06:36:50
【问题描述】:
我正在尝试为我的操作结果实现输出缓存。
在我的操作中,根据某些业务规则返回响应。在我的回复中,我发送错误代码。 如果有任何错误,我不想缓存响应。
跟随动作结果
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 时缓存结果。
我尝试覆盖 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);
}
}
}
有没有其他方法或方法来实现这一点。
谢谢
【问题讨论】:
-
覆盖
OutputCacheAttribute是正确的做法。您还可以在您的操作方法中手动缓存响应对象。 -
更新问题
-
为什么要实现自己的错误响应对象? OutputCache 内置了对正常 HTTP 错误的支持...
-
你能提供同样的参考吗?
标签: asp.net-mvc asp.net-mvc-4 outputcache