1

我正在测试一个正在创建的浏览器,如果我向 webrequest 发送一个存在的 uri,一切都会找到,但是当我发送一个不存在的 uri 时,我得到一个未设置为实例的对象,例如http://www.bgdygjhcu .com

我希望该方法抛出一个未找到的异常。这是方法调用

String stream = await Task.Run(() => web.Navigate("http://www.yahoo2gh.com"));

这是完成工作的方法

public async Task<String> Navigate(string uri)
{

 HttpWebRequest request =(HttpWebRequest)WebRequest.Create(uri);
 try
 {
     using (WebResponse response = request.GetResponse())
     {
         HttpWebResponse httpResponse = (HttpWebResponse)response;
         //Set StatusCode
         StatusCode = httpResponse.StatusCode.ToString();
         //Create Stream
         Stream responseStream = response.GetResponseStream();
         StreamReader reader = new StreamReader(responseStream);

         return reader.ReadToEnd();

     }

 }
 catch (WebException exception)
 {
     using (HttpWebResponse response = (HttpWebResponse)exception.Response)
     {
         // HttpWebResponse httpResponse = (HttpWebResponse)response;
         StatusCodeInteger = (int)response.StatusCode;

         //return httpResponse;
         return "empty";// response.StatusCode.ToString();
     }

 }
}
4

0 回答 0