私は、いくつかのプロパティをチェックし、一般的な失敗の結果を持つ HttpWebRequest の拡張メソッドを作成しました。
私が処理したい失敗の 1 つは、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;
}