2011-06-01 77 views
2

我有一些代码确实是DownloadStringAsync。与我的浏览器我可以得到一些有关错误的信息,因为我打开发送错误消息到浏览器在IIS中。我想知道是否有可能在代码中捕获它。使用System.WebClient捕获500内部服务器错误

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 
    } 
} 

回答

4

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

+0

谢谢。更多细节在这里:http://stackoverflow.com/questions/1167913/webexception-when-reading-a-webexceptions-response-stream – 2011-06-01 18:32:25