WebRequest.GetResponseAsync() throwing exception for other than 200 status code

edx
edx
70 Points
25 Posts

I'm using WebRequest to consume/integrate REST api in .netcore project something like:

WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.Credentials = MyCredentialCache;

try
{
    WebResponse response = await request.GetResponseAsync();
}
catch
{

}

It's working fine if REST api responding with http status code 200.

In case of 400, 404 or 500 http code, throwing exception and go to catch block.

How I can get response in the case of if status code is not 200.

Views: 53
Total Answered: 1
Total Marked As Answer: 0
Posted On: 26-Oct-2020 00:36

Share:   fb twitter linkedin
Answers
Smith
Smith
Participant
534 Points
132 Posts
         

Yes you are right. We need to get response in catch block for protocol errors:

try
{
    WebResponse response = await request.GetResponseAsync();
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError &&
        ex.Response != null)
    {
        var resp = (HttpWebResponse) ex.Response;
        if (resp.StatusCode == HttpStatusCode.NotFound)
        {
            // Do something
        }
        else
        {
            // Do something else
        }
    }
    else
    {
        // Do something else
    }
}
Posted On: 26-Oct-2020 05:44
 Log In to Chat