C# 在运行时确定控制器上的可用操作(handles ActionName属性)
我见过几个类似的问题(但没有一个与ActionName属性相关),答案使用了反射。但是,它不处理的是动作方法是否应用了C# 在运行时确定控制器上的可用操作(handles ActionName属性),c#,asp.net-mvc,asp.net-mvc-5,C#,Asp.net Mvc,Asp.net Mvc 5,我见过几个类似的问题(但没有一个与ActionName属性相关),答案使用了反射。但是,它不处理的是动作方法是否应用了[ActionName]。所以如果我们有 [ActionName('Profile')] public virtual ActionResult AccountProfile(...) 当使用链接解决方案中所示的类似代码时,我不会将方法名称视为Profile,而是将方法名称视为AccountProfile。对于我们的用例来说,这是不好的 我们目前正在使用MVC5。尝试以下方法:
[ActionName]
。所以如果我们有
[ActionName('Profile')]
public virtual ActionResult AccountProfile(...)
当使用链接解决方案中所示的类似代码时,我不会将方法名称视为Profile
,而是将方法名称视为AccountProfile
。对于我们的用例来说,这是不好的
我们目前正在使用MVC5。尝试以下方法:
IList<string> actionNames=new List<string>();
Assembly asm = Assembly.GetExecutingAssembly();
var methodInfos = asm.GetTypes()
.Where(type => typeof(Controller).IsAssignableFrom(type)) //filter controllers
.SelectMany(type => type.GetMethods())
.Where(method => method.IsPublic &&method.CustomAttributes.Any(a=>a.AttributeType==typeof(ActionNameAttribute)));
foreach (var methodInfo in methodInfos)
{
var actionAttribute =
methodInfo.CustomAttributes.First(a => a.AttributeType == typeof(ActionNameAttribute));
var actionName = actionAttribute.ConstructorArguments.First().Value;
actionNames.Add(actionName.ToString());
}
IList actionNames=new List();
Assembly asm=Assembly.getExecutionGassembly();
var methodInfos=asm.GetTypes()
.Where(type=>typeof(Controller).IsAssignableFrom(type))//过滤器控制器
.SelectMany(type=>type.GetMethods())
.Where(method=>method.IsPublic&&method.CustomAttributes.Any(a=>a.AttributeType==typeof(ActionNameAttribute));
foreach(methodInfo中的var methodInfo)
{
var actionAttribute=
首先(a=>a.AttributeType==typeof(ActionNameAttribute));
var actionName=actionAttribute.ConstructorArguments.First().Value;
actionNames.Add(actionName.ToString());
}
通过反射,您可以获得方法的属性。