2

In my .Net MVC app I need to handle server side validation. If there was something wrong with request I get this:

{
   "validationMessage": message
}

with StatusCode = 200. Otherwise of course I get response proper for the call. My issue is that I have troubles checking for validation messages and then deserializing response (I always get null there though fiddler shows me that response comes back).

 public static async Task<Response<T>> Response<T>(HttpResponseMessage response)
    {
        var res = new Response<T>();

        if (response.IsSuccessStatusCode)
        {
            //check for validation messages
            var serverErrorInfo = await response.Content.ReadAsAsync<ServerError>();
            if (serverErrorInfo.ValidationMessage != null)
            {
                res.ErrorInfo = new ErrorInfo(serverErrorInfo.ValidationMessage);
            }
            else
            {
                var result = await response.Content.ReadAsAsync<T>();
                res.IsSuccess = true;
                res.Result = result;
            }
            return res;
        }

What am I doing wrong? Does the response get disposed after first attempt to read it as a ServerError? Since I use generics I cannot first check if there is response and than read the validationMessage.
ServerError Code:

 [JsonObject]
public class ServerError
{
    public string validationMessage{ get; set; }
}

2 Answers 2

2

Probably a deserialization issue. Have you tried ValidationMessage with a capital V in the json response? Also, is serverErrorInfo null entirely, or is just the property ValidationMessage null? Can you check what the value of response.Content is, right before deserialization to ServerError?

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately whole ServerErrorInfo object is null. Once I switched order without conditions (just first read as a response object then as an error where I on puropose create wrong request). Content won't get deserialized as response (which is obvious since there is nothing to deserialize, but also won't deserialize status message. Playing with casing also didn't help. Content length when I try to ReadAsAsync<ServerError> is 36 which points that the validation message must be there.
0

In the end the solution was just using some ugly code:

var serverErrorInfo = JsonConvert.DeserializeObject<ServerError>(await response.Content.ReadAsStringAsync());

I am very unsure why ReadAsAsync fails there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.