2016-07-14 41 views

回答

1

SOLUTION 1個

工作與反射。

小心:這裏假定您的所有操作名稱對控制器都是唯一的。

如果不是這樣,我猜...這個解決方案會失敗。

首先,您需要找到組件。

這可以通過選擇你的API的控制器之一,例如做(他們當然一些其他的方式來找到所需的組件)

var assembly = typeof (HomeController).Assembly; 

現在,我猜你的控制器動作和名稱這樣:

var routeData = RouteTable.Routes.GetRouteData(
       new HttpContextWrapper(HttpContext.Current)); 
var actionName = routeData.GetRequiredString("action"); 
var controllerName = routeData.GetRequiredString("controller"); 

所以下一步是獲取控制器的類型。 可以通過

//you don't need the full name 
var controllerType = assembly.GetTypes().FirstOrDefault(m => m.Name == controllerName + "Controller"); 

var controllerType = assembly.GetType("<namespace>." + controllerName + "Controller"); 

做到無論然後你就可以得到控制的customAttributes

var controllerCustomAttributes = controllerType.GetCustomAttributes(); 

如果你想操作的屬性,你需要得到方法對應於您的操作名稱。

var actionType = controllerType.GetMethods().FirstOrDefault(x => x.Name == actionName); 

話又說回來了,獲得自定義屬性

var actionAttributes = actionType.GetCustomAttributes(); 

解決方案2

這可能是更好的對自己的行爲的自定義添加ActionFilterAttribute,並與OnActionExecuting工作。

例如參見this

+0

看起來像第一個解決方案適合我的使用情況。我不能使用ActionFilterAttribute,因爲我需要在AuthorizationFilter之前執行此代碼(希望在這一點上不要遺漏任何東西)。謝謝ndeedRaphaël。 – Jonathan

相關問題