okThen
okThen

Reputation: 1

What's the proper way to understand which type of ModelState validation error it is?

I am trying to understand whether the error is with JSON format (missing comma and whatnot), or a missing required field (model validation), and return to the user one of the defined custom errors without showing the error message that ModelState has.

if (!ModelState.IsValid) 
{
   var errors = ModelState.Values.SelectMany(x => x.Errors);
}

I've tried looking for exceptions for these errors

var jsonErrors = errors.Where(e => e.Exception is JsonException).ToList();

However Exception property is always null. How come? The only way right now it seems to have some logic filtering on ErrorMessage property, which just seems strange.

Upvotes: -1

Views: 122

Answers (2)

Michał Turczyn
Michał Turczyn

Reputation: 37500

When the model supplied is invalid (for example missing field) you can easily check it as shown below:

var errors = ModelState.Values.SelectMany(x => x.Errors).ToArray();
var errorMesages = errors.Select(x => x.ErrorMessage).ToArray();

enter image description here

When it comes to handling JSON body exceptions, if you'd inspect post requests made by an ASP.NET you'd see (as per my example)

Person.FirstName=fasdfsdgsdfgsdfgsdfgsdfgsdfgsdfgsdfg&Person.LastName=asdfasdfasdfasfasdfasfa&__RequestVerificationToken=CfDJ8O2s-bQ2bZROn_Jr2RHoSWoVCXk6TQzUjVw_1jD36-5-Q02ARXTUpD0I_2O2Gk0gU3mNysSL2C75gndZ5FCWldmLjB3Bw_JDPM0GLRxqIRjryZ0l7lad6H8KLSWD_wZWyNLPsvq_MGd6d_5Fix19EU4

So, body format in ASP.NET pages, is handled internally, and you don't need to worry about it.

Upvotes: 0

stratov
stratov

Reputation: 406

ModelState.IsValid is checking for validation errors. Exception is null because these are validation errors, not the exceptions thrown during json deserialization.

try
{
    var result = JsonConvert.DeserializeObject<MyModel>(jsonString);
}
catch (JsonException ex)
{
    // Handle JSON parsing errors here
}

You can catch Json Exceptions in the code above, when you were in deserialization step.

Upvotes: 1

Related Questions