【问题标题】:Read custom attribute parameter on controller post读取控制器帖子上的自定义属性参数
【发布时间】:2017-07-13 08:23:53
【问题描述】:

我想编写一个自定义属性,我可以用它来装饰 ViewModel 属性,这样,当发布 ViewModel 时,我可以检查哪些发布的属性具有此属性并运行一些逻辑。 我正在尝试设置条件,这不会以任何方式影响验证。

[SetsCondition(SomeEnumerationValue)]
public Fund SelectedFund {get;set;}
...
other properties

然后在控制器中。

[HttpPost]
public IActionResult SelectFund(SelectFundViewModel model){
   if(ModelState.IsValid){
      //check which properties have the SetsCondition Attribute
      //read the SomeEnumerationValue for them
      ..
      //profit
   }
}

只是不太确定我应该从哪种属性继承,或者就此而言,如何检查特定的 ViewModel 属性是否被某个属性修饰。

非常感谢任何帮助

【问题讨论】:

    标签: c# asp.net-core-mvc custom-attributes


    【解决方案1】:

    你可以通过继承Attribute来创建属性:

    [System.AttributeUsage(System.AttributeTargets.Property)]
    public class ConditionAttribute : System.Attribute
    {
        public readonly string value;
        public ConditionAttribute(string value)
        {
            this.value = value;
        }
    }
    

    用法

    [Condition("Some Value")]
    public bool Property { get; set; }
    

    然后您可以通过反射访问此信息: 以下示例取自上面提供的链接:

    System.Reflection.MemberInfo info = typeof(MyClass);
    object[] attributes = info.GetCustomAttributes(true);
    for (int i = 0; i < attributes.Length; i ++)
    {
        System.Console.WriteLine(attributes[i]);
    }
    

    更新链接https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/attributes

    【讨论】:

      【解决方案2】:

      必须继承自 System.ComponentModel.DataAnnotations.ValidationAttribute,并且必须实现 isValid 方法。以https://stackoverflow.com/a/11959931/1270813为例

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-14
        • 2019-10-27
        相关资源
        最近更新 更多