2009-11-18 32 views
2

作爲一個理論練習,幫助我瞭解與MVC相關的成員模型的來龍去脈我想弄清楚我是否可以從外部資源加載權限,爲了原型的目的,我有一個平面文件有一個列表,像這樣:我可以通過派生的AuthorizeAttribute訪問我的控制器/動作/動詞嗎?

Controller1,Method1,Get,Anonymous 
Controller1,Method1,Post,User,Administrator 
Controller2,Method1,Get,Administrator 
Controller2,Method1,Post,Administrator 
Controller2,Method2,Get,User,Editor,Administrator 
Controller2,Method2,Post,Editor,Administrator 

,我可以使用正則表達式來給我,對每一個控制器/動作/動詞組合權限的角色列表解析。

我有我的控制器操作:

[CustomAuthorize] 
public ActionResult Index() 
{ 
    /* Do stuff */ 
} 

我也有我的自定義授權成分:

public class CustomAuthorize : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     /* How do I access which Controller/Action/Verb fired this? */ 
    } 
} 

爲了能夠確定哪些角色可以訪問該控制器飛/動作/動詞,我需要能夠確定哪個控制器/動作/動詞稱爲CustomAuthorize屬性。

我知道我可以性質上我的課,像這樣加:

public class CustomAuthorize : AuthorizeAttribute 
{ 
    public string Controller { get; set; } 
    public string Action { get; set; } 
    public string Verb { get; set; } 
} 

,然後用打電話給我的屬性:

[CustomAuthorize(Controller="Home",Action="Index",Verb="Get")] 
public ActionResult Index() 
{ 
} 

但是,這似乎是一個維護頭痛。如果我可以使用[Authorize]並且讓我的CustomAuthorize.AuthorizeCore方法確定哪個控制器/動作/動詞在AuthorizeCore方法中引用它,那將會很好。

這可能嗎?如果有的話,是否有人可以指導我如何實現這一目標的正確方向?

回答

5

你可能想看看重寫OnAuthorization。它獲得一個具有對Controller和RouteData的引用的AuthorizationContext參數。不過,看看標準AuthorizeAttribute的功能,特別是在緩存方面。您可能會在我的blog關於customizing authorization in MVC的文章中發現一些想法。

+0

我已閱讀您的文章定製授權。翔實。看起來你的建議應該做的伎倆。 – Kilhoffer 2009-11-18 19:04:51

3

嘗試改寫OnAuthorization。

public class TestAttribute : AuthorizeAttribute 
{ 
    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     string controllerName = filterContext.RouteData["controller"]; 
     string actionName = filterContext.RouteData["action"]; 
     string verb = filterContext.HttpContext.Request.HttpMethod; 

     // .. do your processing 
     // if fail... 
     filterContext.Result = new HttpUnauthorizedResult(); 

     base.OnAuthorization(filterContext); 
    } 
} 
+0

雖然沒有關於tvanfosson暗示的緩存的警告,但這是有點危險的。 – 2009-11-18 19:16:24

+0

這是一個恥辱,我不能接受這兩個答案......他們都是有用和信息豐富,都做我所追求的。 – BenAlabaster 2009-11-18 19:17:05

+0

@克雷格 - 作爲一個理論練習,雖然這給了我後來的信息,方法的前三行是我所追求的。正如電視的回答所暗示的,我可以在我的AuthorizeCore()方法中處理其餘部分。 – BenAlabaster 2009-11-18 19:18:36

相關問題