You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET中如何用反射提取MVC Controller Action入参Model的所有属性名

解决方案

你当前代码只读取了动作方法的参数类型名称,没有进一步反射参数类型内部的公共属性,调整后代码如下:

Assembly asm = Assembly.GetAssembly(typeof(Club.Web.MvcApplication));

var controlleractionlist = asm.GetTypes()
        .Where(type => typeof(System.Web.Mvc.Controller).IsAssignableFrom(type))
        .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
        .Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
        .Select(x => new 
        { 
            // 去掉控制器名称的Controller后缀,得到Account这类标识
            Controller = x.DeclaringType.Name.Replace("Controller", ""), 
            // 提取所有参数的类型内部公共属性名拼接
            Input = string.Join(",", x.GetParameters()
                                .SelectMany(p => p.ParameterType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                                .Select(prop => prop.Name))),
            Action = x.Name, 
            ReturnType = x.ReturnType.Name, 
            Attributes = string.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))) 
        })
        .OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList();

// 按你要的格式输出的示例
foreach (var item in controlleractionlist)
{
    Console.WriteLine($"{item.Controller}:{item.Action}:{item.Input}");
}

关键调整说明

  • 控制器名称处理:将默认获取到的AccountController类名移除Controller后缀,匹配你需要的输出前缀
  • 参数属性提取:用SelectMany遍历所有方法参数,再反射每个参数类型的公共实例属性,直接提取属性名拼接,最终得到UserName,Password,CaptchaCode的效果
  • 如果需要过滤特定类型的参数(比如只处理你自定义的业务模型,跳过string、int等基础类型参数),可以在GetProperties前加过滤条件,比如:
    .Where(p => !p.ParameterType.IsValueType && p.ParameterType != typeof(string))
    

内容的提问来源于stack exchange,提问作者Ehsan Akbar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:54:05