Reputation: 1120
Web API 2.0 uses partial validation to validate the request body "Unexpected character encountered while parsing value"
If I send invalid JSON:
{RequiredString_AllowEmptyStrings:, NotRequiredBool: }
It returns:
{
"message": "The request is invalid.",
"modelState": {
"requestParams.RequiredString_AllowEmptyStrings": ["Error reading string. Unexpected token: Undefined. Path 'RequiredString_AllowEmptyStrings', line 1, position 34."],
"requestParams.NotRequiredBool": [
"Unexpected character encountered while parsing value: }. Path 'NotRequiredBool', line 1, position 53.",
"Unexpected character encountered while parsing value: }. Path 'NotRequiredBool', line 1, position 53."
]
}
}
and I I turn it around:
{NotRequiredBool: , RequiredString_AllowEmptyStrings: }
I get:
{
"message": "The request is invalid.",
"modelState": {"requestParams.RequiredString_AllowEmptyStrings": [
"Unexpected character encountered while parsing value: }. Path 'RequiredString_AllowEmptyStrings', line 1, position 54.",
"Unexpected character encountered while parsing value: }. Path 'RequiredString_AllowEmptyStrings', line 1, position 54."
]}
}
The Unexpected character encountered Error occurs only on the last invalid entry.
If the same invalid string is not in last place, Error is Error reading string.
Here is yet another version of the error parsing with a valid entry 2nd.
{RequiredString_AllowEmptyStrings: , NotRequiredBool: false}
returns..
{
"message": "The request is invalid.",
"modelState": {
"requestParams.RequiredString_AllowEmptyStrings": [
"Error reading string. Unexpected token: Undefined. Path 'RequiredString_AllowEmptyStrings', line 1, position 35.",
"The RequiredString_AllowEmptyStrings field is required."
],
All of the above JSON is invalid if I use an online JSON Validator. The Newtonsoft.JSON parser here seems to do a partial validation by key/value pairs, and then stops when fails.
So, my question: Can I pre-parse the JSON Body and add a value in the empty fields so that I can reconstruct valid JSON before the model is validated? Is there some JSON Validator that I can use that does this? I could add this to the WebApi config as a global Validator.
Upvotes: 0
Views: 868
Reputation: 1120
What I ended up doing was calling a JSON Validator that I call at the beginning of the Model Validation.
I posted the code here. https://stackoverflow.com/a/36857080/284169
Upvotes: 0
Reputation: 5850
If you post invalid JSON, the JSON media formatter will fail. No surprises there.
If you want to be able to handle another file format - such as the quasi-but-invalid-JSON examples you've posted above, you can always create a custom System.Net.Http.Formatting.MediaTypeFormatter
.
Upvotes: 2