ModelState.IsValid忽略型别的检查错误

Web Api在Int或DateTime如果传空值的话会自动帮忙设预设值,但是在ModelState.IsValid的时候,却会出现型别上的错误.

解决方式

把Model改成正确,也就是预设允许可以为null.

public class DemoModel                              
 {                                                   
     public int? Id { get; set; }                    
     [Required]                                      
     public string Name { get; set; }                
                                                     
     public DateTime? SelectedDate { get; set; }     
 }         

但是这种解决方式却不能解决我的问题,更多这类情境其实还蛮容易发生在web form转到mvc或web api的时候,因为当你想要翻旧系统的时候,会想要把验证集中放在Model上面,不过即有好几仟个类别可能都已定型,甚至有些是还透过map或者直接对应db的状况,我们不可能去抓出所有会发生错误的状况,一一的去排除掉啊,那我的想法是否能只验证我有定义的attribute,而忽略掉型别的检查呢?如果int或datetime给空值的话,也不会出错呢?其实这个解法是笔者自己写出来的,google也都没有相关的解法,可能是普遍大家都不会这样子干,但是在笔者目前的情境却不得不这样做,所以是否要这样子做就视各位的情境了。

 public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ActionDescriptor.GetCustomAttributes<IgnoreValidateModelAttribute>(false).Any())
            {
                return;
            }

            var httpMethod = actionContext.Request.Method;            
            if (httpMethod == HttpMethod.Get || httpMethod == HttpMethod.Options)
            {
                return;
            }

            var modelResult = new ModelStateDictionary();
            foreach (var item in actionContext.ModelState)
            {
                var errors = item.Value.Errors.FirstOrDefault();
                var hasException = item.Value.Errors.Any(x => x.Exception != null);
                if (hasException)
                {
                    continue;
                }
                modelResult.AddModelError(item.Key, errors.ErrorMessage); //自行新增只有ErrorMessage的部份,而忽略型別轉換的錯誤提示
            }

            if (modelResult.Count > 0)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelResult);
            }

            base.OnActionExecuting(actionContext);
        }
    }

以上述做法可以忽略有expection的错误提醒,但如果有expection的话那model error就会失效了,因为只要有任何expection的状况,就会中止这个属性的检查,不会再加入任何error,也就是说如果我们设定为required,并且属性也没有给nullable的话,而且client端传来又没有给值的话,结果我们的model验证却没有回应此栏位必须填值,就会变得非常怪异。