2013-06-18 66 views
1

嗨,我只是学习反射,我正试图读取控制器中使用属性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 
     } 
     } 
    } 

如果ooked的代码了一下,念你可以看到,在这一点上,我可以从每一个它的参数动作访问评论。

在我们的例子中,返回参数的类型是LoginModelDTO。

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

我怎样才能做到这一点?

+0

在你的示例代码,参数***没有属性* ** - 方法和属性确实;这是故意的吗? –

+0

方法参数或对象属性?我不太清楚你在追求什么.. –

+0

术语明智,这些问题似乎是一些混淆 - 你得到的是“自定义操作”,它们是*方法*,但是你正在调用变量'参数','parameterInfo'等 - 你是否混淆了方法和参数? –

回答

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

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

+0

也有重载的那些方法采用泛型参数而不是Type参数(.NET 4.5+)。例如:http://msdn.microsoft.com/en-us/library/hh194330.aspx –

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

}