.NET Framework Web API 4.7.2必填字段为空时ModelState仍有效求解
问题
在.NET Framework Web API中定义了如下模型:
public partial class RequestData { public int Id { get; set; } [Required(AllowEmptyStrings = false)] public string AccountName { get; set; } [Required(AllowEmptyStrings = false)] public string VendorName { get; set; } [Required] public string Memo { get; set; } public Nullable<bool> IsToBePrinted { get; set; } [Required] public string AccountType { get; set; } [Required] public Nullable<double> Amount { get; set; } public Nullable<bool> IsProcessed { get; set; } public string Ticket { get; set; } public string Response { get; set; } public Nullable<System.DateTime> Updated { get; set; } [Required] public Nullable<int> RequestType { get; set; } [Required] public string TxnId { get; set; } [Required] public string EditSequence { get; set; } [Required] public string ListID { get; set; } [Required] public string TxnLineId { get; set; } }
对应的POST控制器代码如下:
[HttpPost] public ActionResult PostNewRequest([FromBody] RequestData requestData) { try { if (!ModelState.IsValid) { //字段无效时的代码 } else { //字段有效时的代码 } } // 省略后续代码 }
通过SOAP UI发送必填字段为空值(控制器中接收后变为NULL)时,ModelState始终显示为有效,无法触发预期的验证逻辑。
解决方案
1. 修复可空值类型的[Required]失效问题
.NET Framework中,[Required]特性对Nullable<T>(可空值类型)默认不生效——因为null是可空值类型的合法默认值。如果这些字段必须传入有效值(不能为null),直接将其改为非可空值类型:
- 把
Nullable<double> Amount改为double Amount - 把
Nullable<int> RequestType改为int RequestType
非可空值类型在模型绑定阶段,若未收到有效值会自动触发ModelState错误。
2. 补全字符串类型的[Required]验证规则
仅添加[Required]的字符串字段允许空字符串通过验证,必须显式设置AllowEmptyStrings = false,才能同时禁止null和空字符串:
[Required(AllowEmptyStrings = false)] public string Memo { get; set; }
3. 确保全局验证配置生效
检查WebApiConfig.cs,确认已启用全局模型验证过滤器,保证验证逻辑能被触发:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // 启用模型验证 config.Filters.Add(new ValidateModelStateAttribute()); // 其他路由/配置代码 config.MapHttpAttributeRoutes(); // ... } }
4. 匹配请求格式与绑定要求
使用SOAP UI发送请求时,确保Content-Type与[FromBody]的绑定要求一致(通常为application/json),否则模型绑定无法正确识别字段值,导致验证逻辑失效。
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

