从控制器名称获取字符串格式的方法列表

Cod*_*iac 1 c# asp.net-mvc-3

我有以下函数从字符串类型的控制器名称返回操作名称的选择列表:

public ActionResult get_all_action(string controllername)
        {
            Type t = Type.GetType(controllername);
            MethodInfo[] mi = t.GetMethods();

            List<SelectListItem> action = new List<SelectListItem>();

            foreach (MethodInfo m in mi)
            {
                if (m.IsPublic)
                    if (typeof(ActionResult).IsAssignableFrom(m.ReturnParameter.ParameterType))
                    {
                        action.Add(new SelectListItem() { Value = m.Name, Text = m.Name });
                    }
            }

            var List = new SelectList(action, "Value", "Text");

            return Json(List, JsonRequestBehavior.AllowGet);
        }
Run Code Online (Sandbox Code Playgroud)

get_all_action()的参数controllername被传递为例如"AccountController".但抛出异常

MethodInfo[] mi = t.GetMethods();
Run Code Online (Sandbox Code Playgroud)

如:

Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

"AccountController"不是完整的类型名称; 它需要像"YourApp.Whatever.AccountController"GetType()找到它.它也值得明确它所在的汇编,例如:

var thisType = GetType();
Type t = thisType.Assembly.GetType(
    thisType.Namespace + "." + controllerName);
Run Code Online (Sandbox Code Playgroud)

(假设我们的意思是相同的程序集/命名空间)