c# - 使用 System.WebClient 捕获 500 内部服务器错误

标签 c#

我有一些执行DownloadStringAsync的代码。自从我在 IIS 中打开向浏览器发送错误消息后,我可以使用我的浏览器获取有关错误的一些信息。我想知道是否可以在代码中捕获它。

void Process( Job job )
{
   using( WebClient client = new WebClient() )
   {
        client.DownloadStringCompleted += (sender, args ) =>
            DownloadStringCompleted(job,args);

        try
        {
            client.DownloadStringAsync(new Uri(job.url), job);
        }
        catch (WebException e)
        {
            Console.WriteLine(e.Message);
        }
   }
}

void DownloadStringCompleted(Job job, DownloadStringCompletedEventArgs args)
{
   if( args.Error != null )
   {
       // How can i get the response ? Like 500 Internal Server Error
       // this_buggy_page.asp Line 100000
   }
}

最佳答案

如果args.Error != null,它可能会包含WebException的实例;如果是这种情况,那么您可以将其转换为 WebException,然后访问其 Response 属性,您可以将其转换为 HttpWebResponse(对于 HTTP调用),从那里您可以获取标题/正文/等。

关于c# - 使用 System.WebClient 捕获 500 内部服务器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6205822/

相关文章:

c# - Android 在间隔后更新谷歌地图

c# - 扩展方法有什么了不起?

c# - 设置单元测试以使用 Unity 测试 Controller

c# - listView.SelectedItemPosition 始终返回 -1

c# - 处理继承类中参数的最佳方法

c# - 仅使用域和用户名创建 WindowsIdentity

C#:使用 PDFsharp 创建 PDF 表单 (AcroForm)

c# - 如何找到 using 指令中命名空间来自哪个引用文件?

c# - 委托(delegate)和事件

c# - 编写 C# 插件系统