asp.net 为什么HttpWebRequest抛出异常而不是返回HttpStatusCode.NotFound?

68bkxrlz  于 2022-11-26  发布在  .NET
关注(0)|答案(3)|浏览(150)

我尝试使用HttpWebRequest来验证URL的存在。我发现了几个基本上可以做到这一点的示例:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
request.Method = "HEAD";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    return response.StatusCode;
}

然而,如果url确实被破坏了,它就不会返回响应,而是抛出异常。
我将代码修改为:

try
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
    request.Method = "HEAD";
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        return response.StatusCode;
    }
}
catch (System.Net.WebException ex)
{
    var response = ex.Response as HttpWebResponse;
    return response == null ? HttpStatusCode.InternalServerError : response.StatusCode;
}

似乎终于如愿以偿了。
但是我想知道,为什么请求抛出异常,而不是返回带有NotFound状态代码的响应?

yhived7q

yhived7q1#

当网页大量使用状态码而不是所有的都是错误的时候,这会很烦人。这会让处理正文变得很痛苦。我个人使用这种扩展方法来获得响应。

public static class HttpWebResponseExt
{
    public static HttpWebResponse GetResponseNoException(this HttpWebRequest req)
    {
        try
        {
            return (HttpWebResponse)req.GetResponse();
        }
        catch (WebException we)
        {
            var resp = we.Response as HttpWebResponse;
            if (resp == null)
                throw;
            return resp;
        }
    }
}
jm2pwxwz

jm2pwxwz2#

为什么不呢?它们都是有效的设计选项,而HttpWebRequest就是设计成这样工作的。

cbeh67ev

cbeh67ev3#

就像@Will一样,我编写了类似的扩展方法来从WebException中获取字符串形式的响应内容。

/// <summary>
        /// Reads Response content in string from WebException
        /// </summary>
        /// <param name="webException"></param>
        /// <returns></returns>
        public static (HttpStatusCode statusCode, string? responseString) GetResponseStringNoException(this WebException webException)
        {
            if (webException.Response is HttpWebResponse response)
            {
                Stream responseStream = response.GetResponseStream();

                StreamReader streamReader = new(responseStream, Encoding.Default);

                string responseContent = streamReader.ReadToEnd();
                HttpStatusCode statusCode = response.StatusCode;

                streamReader.Close();
                responseStream.Close();
                response.Close();

                return (statusCode, responseContent);
            }
            else
            {
                return (HttpStatusCode.InternalServerError, null);
            }
        }

以上代码是未优化的解决方案。

相关问题