HttpClient IsComplete始终返回false

时间:2015-02-16 11:18:09

标签: c# asp.net asp.net-mvc asynchronous dotnet-httpclient

我试图通过使用HttpClient GetAsync方法授权用户从远程xml Web服务获取数据。不幸的是无论服务器的答案结果如何.IsCompleted alaways在Controller中返回false。我做错了什么? 这是控制器:

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(CredentialsViewModel model)
        {
            if (!ModelState.IsValid) return View("Login");
            var result = ar.AuthenticateUser(model.UserName, model.Password);
            if (!result.IsCompleted)
            {
                ModelState.AddModelError("CustomError", "Вход в систему с указанными логином и паролем невозможен");
                return View("Login");
            }
            FormsAuthentication.SetAuthCookie(model.UserName, false);
            return RedirectToAction("Index", "Home");
        }

如果authorize成功,这就是必须返回布尔值的存储库。

public async Task<bool> AuthenticateUser(string login, string password)
        {
            const string url = @"http://somehost.ru:5555/api/getcountries";
            var client = new HttpClient();
            var encoded = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", login, password)));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encoded);
            var result = await client.GetAsync(url);
            if (result.IsSuccessStatusCode) return true;
            return false;
        }

1 个答案:

答案 0 :(得分:2)

您的控制器操作需要返回一个Task,因为所有异步方法都需要链接下来。

Turtles all the way down帮助我记住:)

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(CredentialsViewModel model)
{
    if (!ModelState.IsValid) return View("Login");
    var result = await ar.AuthenticateUser(model.UserName, model.Password);
    if (!result.IsCompleted)
    {
        ModelState.AddModelError("CustomError", "Вход в систему с указанными логином и паролем невозможен");
        return View("Login");
    }
    FormsAuthentication.SetAuthCookie(model.UserName, false);
    return RedirectToAction("Index", "Home");
}