c# 从webexception中读取错误信息
要从WebException中读取错误信息,您可以使用以下代码:
try
{
// Your web request code here
}
catch (WebException e)
{
if (e.Response != null)
{
using (var errorResponse = (HttpWebResponse)e.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string errorText = reader.ReadToEnd();
// Do something with the error message
}
}
}
}
在这里,我们首先捕获WebException。然后,我们检查其响应是否为null。如果不是,我们可以将其转换为HttpWebResponse并使用StreamReader从其响应流中读取错误消息。最后,我们可以使用读取的错误消息来执行任何必要的操作。
原文地址: https://www.cveoy.top/t/topic/1V9 著作权归作者所有。请勿转载和采集!