2009-07-03 8 views
1

私はBaseControllerを持っています.BaseControllerには個々のアクションではなく、すべてのコントローラーがそれを実行するという属性があります。コントローラ上に属性コードを実行したくないというアクションが1つあります。これをどのように実装できますか?Controller ActionAttributeをオーバーライドできますか?

[MyAttribute] 
public class BaseController : Controller 
{ 

} 

public class WebPageController : BaseController 
    { 
     //How to override attribute executing here? 
     public ActionResult Index() 
     { 
      //do stuff 
     } 

    } 

public class PagePermissionAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     //Do stuff 
    } 
} 

答えて

4

私は完全に誤解されていますので、私は以前の回答を削除しました。これはアクション継承に向けられています。

派生したコントローラのアクションでフィルタを省略するために、私は別の方法で処理すると思います。 1つのアイデアはあなたのフィルタを持つことです - 組み込みのフィルタを使用している場合、それからカスタムフィルタを派生させる必要があります - リフレクションを使用して、実行前に別の属性の存在を確認します。属性が利用可能な場合、それは単に実行されません。

public class SkipAuthorizeAttribute : Attribute 
{ 
    public string RouteParameters { get; set; } 
} 

public class CustomAuthorizeAttribute : AuthorizeAttribute 
{ 
    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     var action = filterContext.RouteData["action"]; 
     var methods = filterContext.Controller 
            .GetType() 
            .GetMethods() 
            .Where(m => m.Name == action); 
     var skips = methods.GetCustomAttributes(typeof(SkipAuthorizeAttribute),false) 
          .Cast<SkipAuthorizeAttribute>(); 

     foreach (var skip in skips) 
     { 
      ..check if the route parameters match those in the route data... 
      if match then return 
     } 

     base.OnAuthorization(); 
    } 
} 

使用法:

[CustomAuthorize] 
public class BaseController : Controller 
{ 
    ... 
} 

public class DerivedController : BaseController 
{ 
    // this one does get the base OnAuthorization applied 
    public ActionResult MyAction() 
    { 
     ... 
    } 

    // this one skips the base OnAuthorization because the parameters match 
    [SkipAuthorize(RouteParameters="id,page")] 
    public ActionResult MyAction(int id, int page) 
    { 
     ... 
    } 
} 
+0

私は完全にあなたの質問を誤解。私は実際の問題に対処するソリューションを更新しました。しかし、はるかに複雑です。 – tvanfosson

関連する問題