Search code examples
c#asp.net-web-apihttpwebrequesthttpwebresponse

400 Bad Request | Receive custom error message or model from ASP.NET Web API


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?


Solution

  • 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());
            }