c# - Asp.net Web Api - 验证属性被调用两次

标签 c# asp.net-mvc asp.net-web-api model-binding asp.net-web-api2

我定义了一个派生自 ValidationAttribute 的新属性。例如

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class ValidateDataAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            // some logic
            return true;
        }
    }

我面临的问题是,对于给定的 Post/Put 请求,“IsValid”方法被调用了两次。如果 ModelState 无效,这将导致重复错误消息。知道可能出了什么问题吗?

示例用法:

public class Test
    {
        [Required]
        [ValidateData]
        public string Data {get;set;}
    }

最佳答案

您已添加 [Required] 和 [ValidateData] 属性。

我想如果您删除 required 属性,这应该可以正常工作,因为它会做同样的事情。两者都继承自ValidateAttribute

公开课测试 { [必需的] 公共(public)字符串数据 {get;set;} }

请同时查看所需的属性类

   // Summary:
//     Specifies that a data field value is required.
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class RequiredAttribute : ValidationAttribute
{
    // Summary:
    //     Initializes a new instance of the System.ComponentModel.DataAnnotations.RequiredAttribute
    //     class.
    public RequiredAttribute();

    // Summary:
    //     Gets or sets a value that indicates whether an empty string is allowed.
    //
    // Returns:
    //     true if an empty string is allowed; otherwise, false. The default value is
    //     false.
    public bool AllowEmptyStrings { get; set; }

    // Summary:
    //     Checks that the value of the required data field is not empty.
    //
    // Parameters:
    //   value:
    //     The data field value to validate.
    //
    // Returns:
    //     true if validation is successful; otherwise, false.
    //
    // Exceptions:
    //   System.ComponentModel.DataAnnotations.ValidationException:
    //     The data field value was null.
    public override bool IsValid(object value);
}

关于c# - Asp.net Web Api - 验证属性被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23822720/

相关文章:

javascript - 使用 JavaScript 正则表达式获取 MVC 样式路由数据(URL 最后一个词)

ASP.NET Core 1.0 - .NET 4.5 项目的 API 引用

c# - 有什么方法可以让端点在带有 C# 的 WebAPI 中使用泛型?

c# - 指定 ValidationGroup 时 ValidationSummary 不起作用

c# - 为什么 JsonSerializer 给空?

asp.net-mvc - 如何使 Html.DisplayFor 显示我从数据库读取的 HTML?

asp.net-mvc - 代码第一个 : does fluent api influence UI?

c# - JSON 序列化 - 将枚举转换为数字

c# - 如何抑制可能的空引用警告

c# - 如何使用 CefSharp 启用 Adob​​e Flash?