html5网站设计工作室源码,网站关键词更换了,wordpress速度加快,永州 网站建设Web Api在Int或DateTime如果传空值的话会自动帮忙设预设值#xff0c;但是在ModelState.IsValid的时候#xff0c;却会出现型别上的错误.解决方式把Model改成正确#xff0c;也就是预设允许可以为nullpublic class DemoModel { …Web Api在Int或DateTime如果传空值的话会自动帮忙设预设值但是在ModelState.IsValid的时候却会出现型别上的错误.解决方式把Model改成正确也就是预设允许可以为nullpublic 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.GetCustomAttributesIgnoreValidateModelAttribute(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验证却没有回应此栏位必须填值就会变得非常怪异。