Jad*_*ded 2 .net networking async-await .net-4.5 dotnet-httpclient
我正在尝试根据新的fw 4.5功能重写旧的网络身份验证逻辑,例如HttpClient和await/async,我在请求和响应之间遇到意外的延迟(大约15秒).我的猜测是因为客户端尝试从IE中查找/使用代理,就像使用旧的HttpRequest/WebClient一样.这是代码:
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 }; ;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个方法用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;
}
Run Code Online (Sandbox Code Playgroud)
身份验证在相应的ViewModel命令中发生:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
调试输出:
[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
Run Code Online (Sandbox Code Playgroud)
当我在HttpClientHandler设置中取消注释UseProxy = false时,延迟消失并且auth没有延迟.即使我没有取消注释UseProxy(每运行一次运行一次),有时也会出现同样的问题.问题是 - 这是一个错误还是什么?试图从服务器端调试,没有发现轮询请求之间的差异.提前致谢.
这不是一个错误.IE的默认设置是尝试自动检测代理,这可能需要30秒.要禁用自动检测,您需要将UseProxy设置为False.
实际上,这些设置与IE并不真正相关.只是IE使用(并设置)系统的默认设置.除非您覆盖它们,否则HttpClient和WebClient都使用系统的默认设置.
至于检测速度,它取决于系统设置.如果在IE或Chrome中禁用自动代理检测,您会发现重启后第一次浏览器打开速度要快得多.这是因为它不会尝试检测代理.代理检测过程在自动代理检测中描述,涉及以下几个步骤:
步骤#2和#3可能需要很长时间,具体取决于您的网络基础架构,甚至可能涉及超时.
| 归档时间: |
|
| 查看次数: |
7417 次 |
| 最近记录: |