【问题标题】:How can an Attribute prevent the execution of an MVC Action?属性如何阻止 MVC 操作的执行?
【发布时间】:2014-01-17 17:16:17
【问题描述】:

MVC 中,OutputCacheAttribute 能够阻止执行它正在装饰的操作(如果存在相关缓存)

如何用自定义属性实现相同的机制?

在其他作品中,我希望能够装饰一个动作,并根据属性内部的逻辑来决定该动作是否应该继续执行。

添加

我已经实现了一种机制,如果对操作的请求带有flushaction=flush_silent 之类的查询字符串,自定义属性(扩展OutputCacheAttribute)会使缓存无效。

我还想做的,不是执行动作:

[JHOutputCache(CacheProfile = "ContentPageController.Index")]
public ActionResult Index(string url)
{
     //custom code that should not execute when flushing the cache
}

【问题讨论】:

    标签: asp.net-mvc custom-attributes outputcache


    【解决方案1】:

    由于JHOutputCache 扩展了源自ActionFilterAttributeOutputCacheAttribute,因此停止执行底层操作非常简单:

    public class JHOutputCacheAttribute : OutputCacheAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (condition)
                filterContext.Result = new EmptyResult();
            else
                base.OnActionExecuting(filterContext);
        }
    }
    

    您可以在此处返回任何有效的ActionResult,包括您可能派生的任何自定义ActionResult

    【讨论】:

    • 正是我想要的! :)
    • 我遇到了另一个问题,问题是带有flushaction=flush_silent 的实际请求被缓存并且不会第二次执行。你知道如何防止它从属性本身中被缓存吗?如果更容易,我可以设置另一个问题。
    • @GiuseppeR 很难说出您要做什么,但听起来VaryByParam 可能是您需要查看的内容。
    • 我设置了另一个问题:stackoverflow.com/questions/21193335/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多