HttpClient IsComplete always return false

2019-08-06 11:07发布

I'm trying to authorize user for get data from remote xml web service by using HttpClient GetAsync method. Unfortunately regardless server answer result.IsCompleted alaways return false in Controller. What I'm doing wrong?
This is Controller:

[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");
        }

And this is repository that actually must return boolean value if authorize was successful.

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条回答
太酷不给撩
2楼-- · 2019-08-06 12:04

Your controller action needs to return a Task as all async methods need to be chained down.

Turtles all the way down helps me remember :)

[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");
}
查看更多
登录 后发表回答