范围数据注释不起作用

时间:2016-07-24 17:39:32

标签: c# range asp.net-core data-annotations modelstate

在我的web api项目中,我有

[HttpPost]
    public void Post([FromBody]AccountDTO accountDto)

AccountD包含一些属性,例如:

public int AccountId { get; protected set; }
    [Range(0,100)]
    public int AccountBalance { get; protected set; }
    [RegularExpression(COMMA_SEPARATED_EMAILS_REGEX)]
    public string Emails { get; set; }

我还添加了过滤器以捕获模型错误:

public void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            throw new InvalidDataException(string.Join(" ", context.ModelState.Keys.SelectMany(key => context.ModelState[key].Errors.Select(x => key + ": " + x.ErrorMessage))));
        }
    }

现在,如果电子邮件字符串无效 - 它会抛出预期的错误,我也尝试了[EmailAddress], [Phone], [Required], [StringLength(3)],并且所有工作正常。 只是[范围(0,100)]不起作用......

我尝试使用accountBallance = 50033333发布AccountDTO并且没有抛出任何错误,也尝试了-5并且我获得了状态200.

我应该在哪里查找错误?...谢谢

2 个答案:

答案 0 :(得分:0)

试试这可能有帮助:

[Required(ErrorMessage = "AccountBalance is required")]
[Range(1.00, 100.00, ErrorMessage = "AccountBalance must be between 1 and 100")]
public Double AccountBalance { get; protected set; }

并确保您使用的是System.ComponentModel.DataAnnotations。

答案 1 :(得分:0)

我删除了protected验证工作。

相关问题