5

We are having an Web API exposed by 3rd party which we do not have any control. It looks like they are wrapping the custom error message model on throwing back 400 (Bad Request).

We get custom error message model when using Postman

{
    "Message": "Site Name Exists",
    "ErrorId": "<some-guid>",
    "ErrorCode": 400,
    "GeneratedTime": "<some-datatime>",
    "RequestedUri": "origin-api-uri"
} 

We tried using HttpWebResponse or WebResponse to get the response from API but it throws exception with 400 code on httpWebRequest.GetResponse(). It does not give us the expected response as we get in Postman but it says 400 (Bad Request) and with default error message, 'The remote server returned an error'.

We want to get original error message as Postman. Any thoughts?

1 Answer 1

6

By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error, or 400 bad Request and this is very painful situation. You need to catch WebException in catch block.

refer to: Exception Handling in ASP.NET Web API

Give it a try.

 catch (WebException ex)
        {
            StreamReader sr = new StreamReader(ex.Response.GetResponseStream());
            Console.WriteLine(sr.ReadToEnd());
        }
Sign up to request clarification or add additional context in comments.

1 Comment

We missed ..GetResponseStream(). Thanks for answer!

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.