asp.net-mvc – 使用Asp.net MVC 4中的OutputCacheAttribute进行条件缓存
发布时间:2021-03-30 21:21:56 所属栏目: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-mvc – 当我不知道内容类型时如何返回文件结果
- asp.net – 经过身份验证的服务不支持跨域javascript回调.
- asp.net-core – 构建asp.net核心错误
- .net – 加密ApplicationServices ConnectionString
- asp.net – 会话固定 – 表单身份验证
- asp.net – 如何使用Inno Setup脚本创建IIS应用程序和应用程
- asp.net-core – 如何在ASP.NET 5中使用“旧”依赖项
- 我可以使用ASP.NET成员身份实体框架吗?
- asp.net-mvc – Visual Studio 2010 Full和ASP.NET MVC 2.0
- asp.net-mvc – ASP.NET Web Api – 将对象发布到自定义动作
推荐文章
站长推荐
热点阅读
