Inheritance and model validation using validation attributes

放肆的年华 提交于 2019-12-25 01:32:44

问题


Overview

It seems that model validators aren't working the way I think they should, let's consider following example:

Code

/// <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; }
}

Questions

I am testing with this request -

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

But when I check in action if my model state is valid it returns true, despite the range validator attribute in the base class of this model. Am I missing something?

Notes

Action signature, model is only used for passing to service and data layers.

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

Updates

  1. I am checking for validation by simply invoking ModelState.IsValid in the Reserve action method.

来源:https://stackoverflow.com/questions/44965841/inheritance-and-model-validation-using-validation-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!