HttpWebRequest.GetResponse对HTTP 304抛出WebException

问题描述:

当Web服务器响应 HttpWebRequest.GetResponse()用HTTP 304(未修改),的GetResponse() thows一个 WebException ,这实在是太令人不可思议了我。这是通过设计还是我缺少明显的东西在这里?

When a web server responds to HttpWebRequest.GetResponse() with HTTP 304 (Not Modified), GetResponse() thows a WebException, which is so very weird to me. Is this by design or am I missing something obvious here?

好了,这似乎是一个被设计的行为和的vexing例外。这可以用此来解决:

Ok, this seems to be a by-design behavior and a perfect example of a vexing exception. This can be solved with this:

public static HttpWebResponse GetHttpResponse(this HttpWebRequest request)
{
    try
    {
        return (HttpWebResponse) request.GetResponse();
    }
    catch (WebException ex)
    {
        if(ex.Response == null || ex.Status != WebExceptionStatus.ProtocolError)
            throw; 

        return (HttpWebResponse)ex.Response;
    }
}