获取参数对象的属性

时间:2013-06-18 11:47:25

标签: c# asp.net-mvc reflection

您好我正在学习反射,我正在尝试阅读使用属性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);
}

我的控制器位于名为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   
         }
       }
    }

如果您对代码进行了一些操作并阅读了注释,您可以看到此时我可以从每个操作中访问它的参数。

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

从这里开始,我想对每个属性的所有属性进行说明,以获得它的CustomAttributes。

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

最简单的一级:

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))) {
     // ...
}

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

答案 1 :(得分:1)

请参阅此SO question

基本上他们使用ReflectedControllerDescriptor来获取ActionDescriptor个实例的列表(我认为你在ControllersInfo.GetAllCustomActionsInController方法中做了类似的事情):

var actionDescriptors = new ReflectedControllerDescriptor(GetType())
  .GetCanonicalActions();
foreach(var action in actionDescriptors)
{
   object[] attributes = action.GetCustomAttributes(false);

   // if you want to get your custom attribute only
   var t4Attributes = action.GetCustomAttributes(false)
    .Where(a => a is T4ValidateAttribute).ToList();

}