1

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;
        }
andrey.shedko
  • 3,128
  • 10
  • 61
  • 121
  • Can you use an HTTP Debugger like Fiddler to see the request/response? Does it just hang at the 'await'? – Jeremy Feb 16 '15 at 11:37

1 Answers1

2

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");
}
hutchonoid
  • 32,982
  • 15
  • 99
  • 104