HttpWebRequest throws "The remote server returned an error: (404) Not Found." for 404

HttpWebRequest throws "The remote server returned an error: (404) Not Found." for 404

我正在尝试发出网络请求:

String url = @"http://whosebug.com/aaaaaaaa.html";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

String responseText;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
   if (response.StatusCode == HttpStatusCode.NotFound) //404
      return "";

   using (StreamReader responseStream = new StreamReader(response.GetResponseStream()))
   {
      responseText = responseStream.ReadToEnd();
   }
}

问题是行:

request.GetResponse();

抛出异常:

为什么 HttpWebRequest 抛出异常;我该如何让它停止?

或者

有人可以建议一种方法或 .NET class,可以 让我与网络服务器对话,并检索 完全有效并非例外 404.

HttpClient has its own issues 将其从考虑中删除。

这是我之前编写的一些代码,欢迎您使用它来处理这种情况。 如果抛出异常,可以通过捕获WebException获取状态码。

public class WebResult
{
    public string Response { get; set; }
    public bool WasSuccessful { get; set; }
    public HttpStatusCode? StatusCode { get; set; }
}

public WebResult GetUrlContents(string url)
{
    try
    {
        var request = (HttpWebRequest)WebRequest.Create(url);

        using (var response = (HttpWebResponse)request.GetResponse())
        using (var responseStream = new StreamReader(response.GetResponseStream()))
        {
            return new WebResult
            {
                WasSuccessful = true,
                Response = responseStream.ReadToEnd(),
                StatusCode = response.StatusCode
            };
        }
    }
    catch (WebException webException)
    {
        return new WebResult
        {
            Response = null,
            WasSuccessful = false,
            StatusCode = (webException.Response as HttpWebResponse)?.StatusCode
        };
    }
}