简体   繁体   中英

Unable to get desired model validation error message in asp.net

I am trying to validate a model and get ModelState validation errors:

Here is my code

[HttpPost]
[Route("")]
public async Task<HttpResponseMessage> PostSomething(RequestModel request)
{
     var modelErrors = ModelState.Values.SelectMany(v => v.Errors);
}

return Request.CreateResponse(HttpStatusCode.OK); 
}

When I debug and watch modelErrors variable I get ErrorMessage = "" and for Exception {"Required property 'object_id' not found in JSON. Path '', line 14, position 1."}.

There is no trace of "Custom error message" defined in RequestModel

public class RequestModel
{
    [JsonProperty("arrival")]
    [Required]
    public DateTime Arrival { get; set; }

    [JsonProperty("departure")]
    [Required]
    public DateTime Departure { get; set; }

    [JsonProperty("object_id")]
    [Required(ErrorMessage = "Custom error message")]
    public int ObjectId { get; set; }
}

Json request

{
  "arrival": "2018-07-01",
  "departure": "2018-07-03"
}

You will have to change:

[JsonProperty("object_id")]
[Required(ErrorMessage = "Custom error message")]
public int ObjectId { get; set; }

to:

[JsonProperty("object_id")]
[Required(ErrorMessage = "Custom error message")]
public Nullable<int> ObjectId { get; set; }

to allow null values for int type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM