Search code examples
c#.netsystem.net.httpwebrequest

Losing error message with Http Status code 503 in System.net.Http library


We have 2 backend services communicating with each other, both of them are using .net framework with System.net.Http library

One of them returns HTTP status code 503 with some response message("data is not available") when certain condition is met, as shown below in the screenshot

enter image description here

the controller code implementation looks like this:

HttpResponseMessage response = new HttpResponseMessage { StatusCode = HttpStatusCode.ServiceUnavailable, ReasonPhrase = "XXXXXX data is currently not available XXXXXXXXX" };
response.Content = new StringContent("XXXXXX is currently not available XXXXXXXXXX");
return response;

the other service which is calling this API is consuming the response and gets this WebException, which is desired case but the problem is, we lose the message("data is not available") being sent from the first service, when I tried to print the response in the debug window, it showed the following result :

HttpWebResponse aresponse = request.GetResponse() as HttpWebResponse;
'HttpWebResponse aresponse = request.GetResponse() as HttpWebResponse' threw an exception of type 'System.Net.WebException'
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2146233079
    HelpLink: null
    InnerException: null
    Message: "The remote server returned an error: (503) Server Unavailable."
    Response: {System.Net.HttpWebResponse}
    Source: "System"
    StackTrace: null
    Status: ProtocolError
    TargetSite: null

As shown in the output message is not what I sent from the first service. It's the default message for HTTP status code 503.

Is there a way for me to read the response content from the WebException?


Solution

  • Found the solution, you can read the response from the System.net.WebException

    catch(WebException ex)
    {
          HttpWebResponse errorResponse = webException.Response as HttpWebResponse;
    
          var statusDescription = errorResponse.StatusDescription;
          if(statusDescription.Contains("XXXXX"))
          {
             // Added the condition here
          }
    }