I want to return the custom error message that I have specified in my data model class to return to user. I've tried creating a filter for override OnActionExecuting(HttpActionContext) but I am still unable to access the custom message. Am I going about this the wrong way or missing something else?
//In data model: public class LogsDto { [Display(Name = "ip")] [Required(ErrorMessage = "IP Address is invalid.")] [DataMember] public string ip { get; set; } } //In WebApiConfig.cs: config.Filters.Add(new ValidateModelAttribute()); //In OnActionExecuting: public override void OnActionExecuting(HttpActionContext context) { if (!context.ModelState.IsValid) { //have tried a variety of methods to locate errormessage context.Response = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.ModelState); } //In Controller: public IHttpActionResult Post([FromBody()]LogsDto request) { try { if (!ModelState.IsValid) return BadRequest(); else { //do stuff } }
I can get a result like below but when I dig down through the (HttpActionContext context), the ErrorMessage is empty and that is what I need.
{"Message": "The request is invalid.","ModelState": {"request.ip": ["Unexpected character encountered while parsing value: ,. Path ip, line 2, position 12.","After parsing a value an unexpected character was encountered: \". Path ip, line 3, position 2." ] } }