简体   繁体   中英

C# WebResponse.GetResponse() returns System.Net.WebException on 404 page not found

I'm new to C#. I noticed that when the server returns anything other then 200 OK I get an

exception. Below is an example of 404 error.

Unhandled Exception: System.Net.WebException: The remote server returned an error: (404) Not Found.

Why should C# generate an exception? This means that I have to use a try / catch block.

None of the examples I've seen mention this problem.

Thanks in advance for any help.

Yes, you need to use a try/catch block because the GetResponse() throws an exeption for status codes in the range 4xx-5xx.

try
{
    response = (HttpWebResponse)request.GetResponse();
    code = response.StatusCode;
}
catch (WebException we)
{
    code = ((HttpWebResponse)we.Response).StatusCode;
}

Yes, it raises an exception. But you can still have the Response and Status from the exception object. So use try/catch, and get the info you need inside the catch block.

如果你真的不想使用 try-catch,我建议你阅读下面的文章: 修复 WebRequest 想要抛出异常而不是返回状态

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

or ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //TLS 1.2 or ServicePointManager.SecurityProtocol = (SecurityProtocolType)768; //TLS 1.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM