I have a custom class with annotations for required fields.
public class User { [DataMember(Name = "firstName")] [Required(ErrorMessage="FIST_NAME_REQUIRED")] public string FirstName { get; set; } [DataMember(Name = "lastName")] [Required(ErrorMessage = "LAST_NAME_REQUIRED")] [Custom(ErrorMessage = "CUSTOM_MESSAGE")] public string LastName { get; set; } }
This class is an argument to the POST API call.
[HttpPost] public HttpResponseMessage Create(User request) { var response = new ApiResponse(); if (request != null && ModelState.IsValid) { [Code here] } else { response.Success = false; response.Message = ModelState.Values.Count() > 0 ModelState.Values.Select(value => value.Errors).Select(error => error.First().ErrorMessage).Aggregate((result, next) => result + ", " + next) : string.Empty ; return Request.CreateResponse(HttpStatusCode.OK, response); } }
My problem is that when I call an API controller action without a name, for example, I get the default error message “FirsName property required”. instead of my custom error message "FIRST_NAME_REQUIRED".
The error message for Custom validator is working fine.
I could not find any information about this on Google, so there may be something very specific to my code, but I can not think of anything.
Any idea?
Julie source share