0

I have tried the below answer, but all I get is an empty string.

WebException how to get whole response with a body?

I have tested hitting the endpoint through postman, and I get the json response (error response) as I expect. But when I try and hit that endpoint in .net, the response doesn't seem to contain the JSON. The above questions answer results in an empty string.

catch (WebException ex)
        {

            var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();

            dynamic obj = JsonConvert.DeserializeObject(resp);
            var messageFromServer = obj.error.message;
            return messageFromServer;

        }

And when I try to just return the ReadToEnd() string, it's empty. Just "".

But as stated before, the endpoint I'm hitting is returning the JSON correctly.

{
    "Message" : "The number could not be found"
}
cphilpot
  • 1,155
  • 3
  • 17
  • 39
  • What do you have in ex.Message? – Grzesiek Danowski Oct 31 '18 at 15:37
  • Error responses *don't* contain bodies in most cases. You have to verify there's anything to read before trying to read it. A 401, 403 or 500 won't contain bodies. Check the [WebException.Status](https://learn.microsoft.com/en-us/dotnet/api/system.net.webexception.status?view=netframework-4.7.2) property before trying to read the response – Panagiotis Kanavos Oct 31 '18 at 15:49
  • The code should work like this. Are you sure you don't have another HTTP error in your test? It's probably another error than "The number could not be found" – Reno Oct 31 '18 at 17:02
  • @GrzesiekDanowski It just says "An error occurred" – cphilpot Nov 01 '18 at 14:45
  • @Reno It is. It says "An error occurred" Which is entirely unhelpful. I need the specific error from the server. This is standard flow for api servers. If Panagiotis is correct and the body on an error response isn't provided then that's frustrating and kind of sad. MS, stop trying to force your opinions on developers. Just give me the entire response... – cphilpot Nov 01 '18 at 14:45
  • What status code you get in Postman? And is the same behawior if you use HttpClient? – Grzesiek Danowski Nov 02 '18 at 18:05

1 Answers1

0

It's example only, in your case you should use the following:

dynamic obj = JsonConvert.DeserializeObject(resp);
var messageFromServer = obj.Message;

Please, compare JSON from the linked question:

{  
   "count":0,
   "startIndex":0,
   "status":1,
   "statusCode":500,
   "error":{  
      "message":"Invalid username or password."
   }
},

and yours:

{
    "Message" : "The number could not be found"
}
isnullxbh
  • 807
  • 13
  • 20