asp.net-mvc – 使用Asp.net MVC 4中的OutputCacheAttribute进行条件缓存
发布时间:2021-03-30 18:02:55 所属栏目:asp.Net 来源:互联网
导读:我正在尝试为我的操作结果实现输出缓存. 在我的操作中,根据某些业务规则返回响应.在我的回复中,我发送错误代码.如果有任何错误,我不想缓存响应. 在行动结果中 class Response { public int ErrorCode { get; set; } public string Message { get; set; }} [Ou
我正在尝试为我的操作结果实现输出缓存. 在我的操作中,根据某些业务规则返回响应.在我的回复中,我发送错误代码.如果有任何错误,我不想缓存响应. 在行动结果中 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); } } } 有没有其他方法或方法来实现这一目标. 谢谢 解决方法您可以创建自己的自定义属性,根据结果错误代码忽略[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(); } } } (编辑:河池站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- asp.net – 确定当前页面是否需要授权?
- .net – IIS 6.0和ASPX中的404自定义错误不起作用
- asp.net-mvc-3 – 用于ASP的Telerik扩展. NET MV
- 有没有办法将内部控件放在ASP.NET自定义控件中?
- asp.net-mvc – 寻找第三方CMS与MVC网站集成
- asp.net-mvc – MVC Razor – 如何向自己提交表单
- ASP.NET MVC 4和Razor 2:View引擎不再支持xml?
- 下载期间的ASP.net内存使用情况
- ASP.NET中TextBox使用Ajax控件显示日期不全的问题
- 利用ASP.NET MVC和Bootstrap快速搭建个人博客之后
热点阅读