使用验证属性进行继承和模型验证

时间:2017-07-07 08:16:23

标签: c# .net validation asp.net-web-api model

概述

模型验证器似乎没有按我认为应该的方式工作,让我们考虑以下示例:

代码

/// <summary>
///     Model that holds reserve data passed to <see cref="ReserveController"/> Commit and Cancel actions.
/// </summary>
public class BaseReserveData
{
    /// <summary>
    ///     Customer identifier in operator's database.
    /// </summary>
    [Required]
    [Range(1, int.MaxValue)]
    public int cust_id { get; set; }
    /// <summary>
    ///     Reserve identifier in operator's database.
    /// </summary>
    [Required]
    public long reserve_id { get; set; }
}
/// <summary>
///  Model that holds base reserve data plus amount and request identifier that are passed
///  to <see cref="ReserveController"/> Reserve and Debit actions.
/// </summary>
public class TransactionalReserveData : BaseReserveData
{
    /// <summary>
    ///     The amount to be reserved.
    /// </summary>
    [Required]
    public decimal amount { get; set; }
    /// <summary>
    ///     Request identifier.
    /// </summary>
    [Required]
    [Range(1, int.MaxValue)]
    public long req_id { get; set; }
}

问题

我正在测试此请求 -

host/api/Reserve/Reserve?cust_id=0&reserve_id=1&amount=1.01&req_id=2

但是当我检查我的模型状态是否有效时,它返回true,尽管此模型的基类中有range validator属性。我错过了什么吗?

备注

动作签名,模型仅用于传递到服务和数据层。

[HttpPost]
[Route("Reserve")]
public IHttpActionResult Reserve([FromUri]TransactionalReserveData trxReserveData, [FromBody]BetsData bet)

更新

  1. 我只是在预约操作方法中调用ModelState.IsValid来检查验证。

0 个答案:

没有答案