C#HttpWebRequest忽略HTTP 500错误 [英] C# HttpWebRequest ignore HTTP 500 error
问题描述
我正在尝试使用C#4.0中的WebRequest类下载页面.由于某种原因,此页面可以正确返回所有内容,但是带有HTTP 500内部错误代码.
I'm trying to download a page using the WebRequest class in C#4.0. For some reason this page returns all the content correctly, but with a HTTP 500 internal error code.
Request.EndGetResponse(ar);
当页面返回HTTP 500或404时,此方法将引发WebException.我该如何忽略呢?我知道它返回500,但是我仍然想阅读页面/响应的内容.
When the page returns HTTP 500 or 404, this method throws a WebException. How can I ignore this? I know it returns 500 but I still want to read the contents of the page / response.
推荐答案
通过查看WebExeption公开的响应对象,可以尝试使用try/catch块来捕获异常,并在出现HTTP 404或500错误的情况下进行其他处理.课.
You can a try / catch block to catch the exception and do additional processing in case of http 404 or 500 errors by looking at the response object exposed by the WebExeption class.
try
{
response = (HttpWebResponse)Request.EndGetResponse(ar);
}
catch (System.Net.WebException ex)
{
response = (HttpWebResponse)ex.Response;
switch (response.StatusCode)
{
case HttpStatusCode.NotFound: // 404
break;
case HttpStatusCode.InternalServerError: // 500
break;
default:
throw;
}
}
这篇关于C#HttpWebRequest忽略HTTP 500错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!