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

edx
edx
Member
506 Points
24 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: 1117
Total Answered: 1
Total Marked As Answer: 1
Posted On: 26-Oct-2020 00:36

Share:   fb twitter linkedin
Answers
Smith
Smith
None
2568 Points
74 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
thanks
 - edx  17-Mar-2021 22:14
 Log In to Chat