Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 707
Ashokan Sivapragasam Avatar asked Jul 18 '19 09:07

Ashokan Sivapragasam


People also ask

How does Web API handle 400 error?

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.

How does ASP net handle Web API errors?

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.

What is 400 error in REST API?

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).


1 Answers

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());
        }
like image 151
Mehran Khan Avatar answered Sep 26 '22 23:09

Mehran Khan