HttpClient IsComplete always return false

孤街浪徒 提交于 2019-12-11 06:28:20

问题


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:


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


来源:https://stackoverflow.com/questions/28540237/httpclient-iscomplete-always-return-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!