Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在运行时确定控制器上的可用操作(handles ActionName属性)_C#_Asp.net Mvc_Asp.net Mvc 5 - Fatal编程技术网

C# 在运行时确定控制器上的可用操作(handles 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]
。所以如果我们有

[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());
}

通过反射,您可以获得方法的属性。