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?
BadRequest: 400 Error A 400 error, BadRequest, is used when you have validation errors from data posted back by the user. You pass a ModelStateDictionary object to the BadRequest method and it converts that dictionary into JSON which, in turn, is passed back to your HTML page.
You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception.
The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (for example, malformed request syntax, invalid request message framing, or deceptive request routing).
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With