HttpWebRequest.GetResponse在HTTP 304上抛出WebException

Ant*_*lev 29 .net http httpwebrequest http-status-code-304

当Web服务器HttpWebRequest.GetResponse()使用HTTP 304(未修改)进行响应时,GetResponse()发生了a WebException,这对我来说非常奇怪.这是设计还是我错过了一些明显的东西?

Ant*_*lev 47

好吧,这似乎是一种设计行为,是一个令人烦恼的例外的完美例子.这可以通过以下方法解决:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这适用于大多数情况,但某些Web服务器在返回404错误时可能会返回响应正文.在这种情况下,上面的代码将处理404,因为它对待304! (3认同)

Gar*_*ack 7

这确实是一个令人沮丧的问题,可以通过使用以下扩展方法类和调用request.BetterGetResponse()来解决这个问题.

//-----------------------------------------------------------------------
//
//     Copyright (c) 2011 Garrett Serack. All rights reserved.
//
//
//     The software is licensed under the Apache 2.0 License (the "License")
//     You may not use the software except in compliance with the License.
//
//-----------------------------------------------------------------------

namespace CoApp.Toolkit.Extensions {
    using System;
    using System.Net;

    public static class WebRequestExtensions {
        public static WebResponse BetterEndGetResponse(this WebRequest request, IAsyncResult asyncResult) {
            try {
                return request.EndGetResponse(asyncResult);
            }
            catch (WebException wex) {
                if( wex.Response != null ) {
                    return wex.Response;
                }
                throw;
            }
        }

        public static WebResponse BetterGetResponse(this WebRequest request) {
            try {
                return request.GetResponse();
            }
            catch (WebException wex) {
                if( wex.Response != null ) {
                    return wex.Response;
                }
                throw;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在http://fearthecowboy.com/2011/09/02/fixing-webrequests-desire-to-throw-exceptions-instead-of-returning-status/上关于此主题的博文中阅读更多相关信息.


Seb*_*ian 5

避免这种System.WebException情况的方法是将AllowAutoRedirect属性设置 为false。这将禁用WebRequest. 它似乎被 304 重定向请求破坏了,因为它不是最严格意义上的真正重定向。当然,这意味着3xx必须手动处理其他重定向请求。