Skip to main content
 首页 » 编程设计

c#之获取参数对象的属性

2024年02月13日12bluestorm

您好,我正在学习反射,我正在尝试读取 Controller 中使用属性 T4ValidateAttribute 修饰的操作的参数。

举个例子:

 public class LoginModelDTO 
{       
    [Required(ErrorMessage = "Username is required")] 
    [MaxLength(50, ErrorMessage = "Username should not have more then 50 chars")] 
    [MinLength(25 , ErrorMessage = "Username should have at least 25 chars")] 
    public string UserName { get; set; } 
 
    [Required(ErrorMessage = "Password is required")] 
    [StringLength(25)] 
    public string Password { get; set; } 
 
    public bool RememberMe { get; set; } 
} 
 
[T4ValidateAttribute] 
public bool LogIn(LoginModelDTO modelDTO) 
{ 
    return m_loginService.Login(modelDTO); 
} 

我的 Controller 在一个名为 prokect.WebApi 的项目中,而我的 DTO 在一个名为 project.DomainServices.Contracts 的项目中。 我不会添加 ControllerInfo,因为如果你们认为需要它,我会添加它。

 //This code get all the controllers that inherit from the BaseApiController      
 List<Type> controllers = ControllersInfo.GetControllers<BaseApiController>("project.WebApi"); 
 
 foreach (var controller in controllers) 
 { 
    //This retrives a Dictionary that has the key the method name and the valie an array of ParameterInfo[] 
     var actions = ControllersInfo.GetAllCustomActionsInController(controller, new T4ValidateAttribute()); 
     foreach (var parameterInfose in actions) 
     { 
         var parameters = parameterInfose.Value; 
         foreach (var parameterInfo in parameters) 
         { 
            //This is where I do not knwo what to do    
         } 
       } 
    } 

如果您稍微看一下代码并阅读注释,您会发现此时我可以从每个操作访问它的参数。

在我们的示例中,返回参数的类型为 LoginModelDTO。

从这里开始,我想为每个属性遍历此对象的所有属性以获取它的 CustomAttributes。

我怎样才能做到这一点?

请您参考如下方法:

在最简单的层面上:

var attribs = Attribute.GetCustomAttributes(parameterInfo); 

如果您感兴趣的所有属性都有一个共同的基类型,您可以将其限制为:

var attribs = Attribute.GetCustomAttributes(parameterInfo, 
                    typeof(CommonBaseAttribute)); 

然后您只需遍历 attribs 并选择您关心的内容。如果您认为最多只有一种特定类型:

SomeAttributeType attrib = (SomeAttributeType)Attribute.GetCustomAttribute( 
       parameterInfo, typeof(SomeAttributeType)); 
if(attrib != null) { 
     // ... 
} 

最后,如果您只是想知道属性是否已声明,这比 GetCustomAttribute[s] 便宜得多:

if(Attribute.IsDefined(parameterInfo, typeof(SomeAttributeType))) { 
     // ... 
} 

但是请注意,在您的示例中,参数没有属性。