DataAnnotation for Required property

后端 未结 4 849
生来不讨喜
生来不讨喜 2020-12-05 00:24

First it works, but today it failed!

This is how I define the date property:

[Display(Name = \"Date\")]
[Required(ErrorMessage = \"Date of Submissio         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 00:46

    I have added a ModelValidationFilterAttribute and made it work:

    public class ModelValidationFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.ModelState.IsValid)
            {
                // Return the validation errors in the response body.
                var errors = new Dictionary>();
                //string key;
                foreach (KeyValuePair keyValue in actionContext.ModelState)
                {
                    //key = keyValue.Key.Substring(keyValue.Key.IndexOf('.') + 1);
                    errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
                }
                //var errors = actionContext.ModelState
                //    .Where(e => e.Value.Errors.Count > 0)
                //    .Select(e => new Error
                //    {
                //        Name = e.Key,
                //        Message = e.Value.Errors.First().ErrorMessage
                //    }).ToArray();
    
                actionContext.Response =
                    actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors);
            }
        }
    }
    

    You can either add [ModelValidation] filter on the actions. Or add it into Global.asax.cs:

    GlobalConfiguration.Configuration.Services.RemoveAll(
    typeof(System.Web.Http.Validation.ModelValidatorProvider),
    v => v is InvalidModelValidatorProvider);
    

    In this way, I continue to use the original data annotation.

    Reference

提交回复
热议问题