0

我已经为 HttpWebRequest 编写了一个扩展方法,它将检查一些属性并具有一般的失败结果。

我要处理的故障之一是 407 Proxy Authentication Required。发生这种情况时,我向用户显示一个登录掩码,并使用返回的用户/密码作为凭据并开始一个新请求。

我目前面临的问题是我无法使用原始请求(现在使用代理凭据)重新发出请求。我也没有从旧请求中获取数据来填写新请求:/

你如何在 C# 中优雅地处理 407?


我目前要使用的代码如下所示:

public static class WebRequestExtension
{
    public static HttpWebResponse GetResponseWithProxyCheck(this HttpWebRequest request)
    {
        return GetResponseWithProxyCheck(request, 0);
    }
    private static HttpWebResponse GetResponseWithProxyCheck(this HttpWebRequest request, int numberOfCalls)
    {
        try
        {
            if (request.Proxy != null && credential != null)
                request.Proxy.Credentials = credential;
            return (HttpWebResponse)request.GetResponse();
        }
        catch (WebException w)
        {
            var webResponse = w.Response as HttpWebResponse;
            if (webResponse.StatusCode == HttpStatusCode.ProxyAuthenticationRequired && numberOfCalls < 3)
            {
                ProxyDialog pd = new ProxyDialog();
                var ret = pd.ShowDialog();
                if (ret == DialogResult.OK)
                {
                    credential = new NetworkCredential(pd.User, pd.Password);
                    var newRequest = (HttpWebRequest);// somehow duplicate the old Request
                    return newRequest.GetResponseWithProxyCheck(numberOfCalls + 1);
                }
            }
            throw;
        }
    }

    private static ICredentials credential;
}
4

0 回答 0