2014-09-12 82 views
7

叫我有一個自定義AuthorizationFilter類來處理授權給我的API。 現在,我需要添加一些屬性將被只讀在 某些情況下的方法來提高它。如何知道哪些控制器方法從網絡API授權過濾

我可以從actionContext.ControllerContext得到控制,但:

我怎樣才能知道哪些Controller方法將我的自定義AuthorizeAttribute類的IsAuthorized方法叫什麼名字?所以我可以通過反射來獲得它的屬性。

編輯:添加更多的信息 -

如果我接到一個電話像localhost/api/myapi/?id=4 我想,這將在控制器類似GetById(int id).

這樣我可以檢查執行的方法的真實姓名如果該方法有任何我需要添加的自定義屬性。

+0

鎂試試這個我刪除了我的答案,我誤解你的問題。你有沒有看到@亨利克庫克的答案?這對我的作品 – wal 2014-09-21 00:49:55

回答

18

在網頁API 2您可以訪問操作名稱:

actionContext.ActionDescriptor.ActionName 
+6

請添加更多的細節來解釋是怎麼回事。 – twoleggedhorse 2014-09-20 05:53:55

+4

@twoleggedhorse還有什麼需要解釋呢? – wal 2014-09-21 00:48:16

+0

你不能在'actionContext'中添加web api 2.對於1個人已經實現了基類'ApiController',所以你不能在控制器上實現另一個基類('AuthorizeAttribute')因此,幾個人添加的原因瞭解更多細節 – 2017-04-19 20:49:49

1

你沒有張貼任何代碼,但你不能看的RouteData在HttpActionContext?

public class MyAuthAttribute : AuthorizeAttribute 
{ 
    protected override bool IsAuthorized(HttpActionContext actionContext) 
    { 
     var routeData = actionContext.ControllerContext.RouteData; 

     //If you don't have an action name, I've assumed "index" is the default. 
     var actionName = routeData.Values.ContainsKey("id") ? routeData.Values["id"].ToString() : "Index"; 

     //you can then get the method via reflection... 
     var attribs = actionContext.ControllerContext.Controller.GetType() 
        .GetMethod(actionName, BindingFlags.Public | BindingFlags.Instance) 
        .GetCustomAttributes(); 

     //Do something... 

     return base.IsAuthorized(actionContext); 
    } 
} 
0

那麼你可以從路由數據

// Gets controller name  
var controller = routeData.GetRequiredString("controller"); 

// Gets action name 
var action = routeData.GetRequiredString("action");