.net核心模型状态即使在必填字段为空的情况下也有效

时间:2019-10-10 08:50:48

标签: asp.net-web-api .net-core modelstate

我有这个模型:

public class FieldMapViewModel
{
    public int Id { get; set; }
    [Range(1, int.MaxValue, ErrorMessageResourceName = "RangeErrorMessage", ErrorMessageResourceType = typeof(Resources))] public int FeedId { get; set; }
    [Range(1, int.MaxValue, ErrorMessageResourceName = "RangeErrorMessage", ErrorMessageResourceType = typeof(Resources))] public int FieldId { get; set; }
    [Required(ErrorMessageResourceName = "RequiredErrorMessage", ErrorMessageResourceType = typeof(Resources)), StringLength(100, ErrorMessageResourceName = "StringLengthErrorMessage", ErrorMessageResourceType = typeof(Resources))] public string Path { get; set; }
}

如您所见,路径是必需的, FieldId FeedId 的范围是1到int.MaxValue。 因此,在我的控制器中,此行应返回 BadRequest

if (!ModelState.IsValid) return BadRequest(ModelState);

但不是。 我通过的模型如下:

enter image description here

在这种情况下, FieldId Path ModelState 均应失败。 这是完整的代码:

/// <summary>
/// Creates a new fieldMap
/// </summary>
/// <param name="fieldMap">The fieldMap</param>
/// <returns></returns>
[HttpPost]
[ProducesResponseType(typeof(FieldMap), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> CreateAsync(FieldMapViewModel fieldMap)
{
    if (fieldMap == null) return BadRequest();
    if (!ModelState.IsValid) return BadRequest(ModelState);

    var request = ModelFactory.Create(fieldMap);

    _fieldMapService.Create(request);
    await _fieldMapService.SaveChangesAsync();

    return Created(nameof(Get), new Sxp.Web.ActionResult<FieldMap>(request, string.Format(Resources.EntityCreated, "fieldMap")));
}

谁能告诉我为什么它没有被捡起?

0 个答案:

没有答案