解决方案 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。