【问题标题】:RequiredIf not working for int property必需如果不适用于 int 属性
【发布时间】:2015-10-13 12:17:26
【问题描述】:

我正在使用 ExpressiveAnnotations 对我的属性进行一些验证。现在,我遇到了一个问题,我无法验证 int 类型的属性:

public class MyModel {

    public string AorB { get; set; }

    [RequiredIf("AorB == 'B'")]
    public string Foo { get; set; }

    [RequiredIf("AorB == 'B'")]
    public int Bar { get; set; }
}

我的控制器

public class MyController : ApiController
{

    public IHttpActionResult Post(MyModel myModel)
    {
        if(ModelState.IsValid)
        {
            // do something
            return Ok();
        }

        return BadRequest("To bad");
    }
}

当我发布时:{"AorB" : "B", "Bar" : 1} 我收到一条消息“由于 AorB == B 需要 Foo”并且系统返回 BadRequest

当我 POST 时:{"AorB" : "B", "Foo" : "foo"} 我没有收到消息,系统返回 Ok。

【问题讨论】:

    标签: c# asp.net-web-api2 expressiveannotations


    【解决方案1】:

    好的,它没有验证的原因是因为它应该是 int?所以模型看起来像这样:

    public class MyModel {
    
        public string AorB { get; set; }
    
        [RequiredIf("AorB == 'B'")]
        public string Foo { get; set; }
    
        [RequiredIf("AorB == 'B'")]
        public int? Bar { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多