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