我試圖根據新的fw 4.5功能(如HttpClient和await/async)重寫舊網絡身份驗證邏輯,並且遇到請求和響應之間的意外延遲(大約15秒)。我的猜測是,這是因爲客戶端試圖從IE瀏覽器中查找/使用代理服務器,就像使用舊的HttpRequest/WebClient一樣。下面的代碼:新的HttpClient代理設置問題
public static async Task<AuthResult> GetDataFromServiceAsync(string url, string login, string password)
{
Debug.WriteLine("[" + DateTime.Now + "] GetDataFromServiceAsync");
var handler = new HttpClientHandler { Credentials = new NetworkCredential(login, password)/*, UseProxy = false*/ };
var client = new HttpClient(handler) { MaxResponseContentBufferSize = Int32.MaxValue };
try
{
var resp = await client.GetAsync(new Uri(url));
var content = resp.Content.ReadAsStringAsync().Result;
var auth = ParseContent(content);
Debug.WriteLine("[" + DateTime.Now + "] Returning AuthResult : " + auth);
return new AuthResult { Success = auth, Exception = null};
}
catch (Exception exception)
{
//
Debug.WriteLine("[" + DateTime.Now + "] Returning error AuthResult : " + exception.Message);
return new AuthResult { Success = false, Exception = exception }; ;
}
}
}
這種方法是包裹着從API等方法,實際上什麼也不做相關的當前情況:
public async Task<AuthResult> IsAuthenticated(string login, string password)
{
Debug.WriteLine("[" + DateTime.Now + "] Starting ISAuthenticationService.IsAuthenticated");
// ... (cut) ...
// async
var authResult = await ISHelpers.GetDataFromServiceAsync(url, login, password);
Debug.WriteLine("[" + DateTime.Now + "] Ending ISAuthenticationService.IsAuthenticated");
return authResult;
}
認證發生在相應的視圖模型的命令:
private async void ExecuteAuthenticationCommand()
{
// Test stub
//var authService = new Helpers.MockupAuthenticationService();
var authService = new Helpers.ISAuthenticationService();
var auth = await authService.IsAuthenticated(Login, Password);
if (auth.Success)
{
MessageBox.Show("Authentication success");
Messenger.Default.Send<LoginDataItem>(_dataItem);
}
else
{
MessageBox.Show(auth.Exception.Message, "Incorrect login data");
}
}
調試輸出:
[27.06.2012 16:54:10] Starting ISAuthenticationService.IsAuthenticated
[27.06.2012 16:54:10] GetDataFromServiceAsync
[27.06.2012 16:54:25] ParseContent in GetDataFromServiceAsync
[27.06.2012 16:54:25] Returning AuthResult : True
[27.06.2012 16:54:25] Ending ISAuthenticationService.IsAuthenticated
當我在HttpClientHandler設置中取消註釋UseProxy = false時,延遲消失且auth沒有延遲。即使我沒有取消註釋UseProxy(每運行大約十次運行一次),問題也會發生。問題是 - 是一個錯誤還是什麼?試圖從服務器端進行調試,發現輪詢請求之間沒有差異。提前致謝。
爲什麼有時候檢測會立即發生?爲什麼HttpClient甚至與IE有關?閱讀MSDN並沒有找到任何的參考。 – Jaded