【问题标题】:Detect whether or not a specific attribute was valid on the model检测特定属性在模型上是否有效
【发布时间】:2010-06-15 19:28:16
【问题描述】:

从 System.ComponentModel.DataAnnotations.ValidationAttribute 创建了我自己的验证属性后,我希望能够从我的控制器中检测该特定属性在模型上是否有效。

我的设置:

public class MyModel
{
    [Required]
    [CustomValidation]
    [SomeOtherValidation]
    public string SomeProperty { get; set; }
}

public class CustomValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        // Custom validation logic here
    }
}

现在,我如何从控制器检测 CustomValidationAttribute 的验证是否成功?

我一直在查看 ModelState 中 ModelError 的 Exception 属性,但我无法从我的 CustomValidationAttribute 中为其添加自定义异常。

现在我已经求助于检查 ModelState 中的特定错误消息:

public ActionResult PostModel(MyModel model)
{
    if(ModelState.Where(i => i.Value.Errors.Where((e => e.ErrorMessage == CustomValidationAttribute.SharedMessage)).Any()).Any())
        DoSomeCustomStuff();

    // The rest of the action here
}

并将我的 CustomValidationAttribute 更改为:

public class CustomValidationAttribute : ValidationAttribute
{
    public static string SharedMessage = "CustomValidationAttribute error";

    public override bool IsValid(object value)
    {
        ErrorMessage = SharedMessage;
        // Custom validation logic here
    }
}

我不喜欢依赖字符串匹配,这样 ErrorMessage 属性有点被滥用了。

我有什么选择?

【问题讨论】:

    标签: c# asp.net-mvc validation model-validation


    【解决方案1】:

    我认为在 CustomValidationAttribute 中有一个名为 ExceptionType 的枚举是有意义的,它清楚地标识了引发的异常类型。

    在控制器中,我们可以检查异常类型并进行相应的处理。

    try
    {
    
    }
    Catch(Exception e)
    {
     Switch(e.ExceptionType)
     {
         case ExceptionType.Val1:
    
           // Handle accordingly  
           break;
     }
    }
    

    【讨论】:

    • 嗯,我不明白这将如何与模型绑定一起使用。异常将在调用操作之前发生。我也不确定将设计基于在 CustomValidationAttribute.IsValid 方法中抛出异常是否是一个好主意。我的意思是,如果我用它验证的内容无效,我应该简单地返回 false。
    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 2020-06-29
    • 2019-11-20
    • 2019-04-30
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多