我的问题和这个问题非常相似。我有一个AuthenticationService
类,它使用HttpClient
的PostAsync()
方法,并在从ASP项目运行它时永远不返回结果,但是当我在控制台应用程序中实现它时,它可以正常工作。
这是我的认证服务类:
public class AuthenticationService : BaseService
{
public async Task<Token> Authenticate (User user, string url)
{
string json = JsonConvert.SerializeObject(user);
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.PostAsync(url, content);
string responseContent = await response.Content.ReadAsStringAsync();
Token token = JsonConvert.DeserializeObject<Token>(responseContent);
return token;
}
}
这里就是悬挂的地方:HttpResponseMessage response = await _client.PostAsync(url, content);
这是我的控制器调用服务的地方:
public ActionResult Signin(User user)
{
// no token needed to be send - we are requesting one
Token token = _authenticationService.Authenticate(user, ApiUrls.Signin).Result;
return View();
}
以下是我使用Console应用程序测试该服务的示例,结果运行良好。
class Program
{
static void Main()
{
AuthenticationService auth = new AuthenticationService();
User u = new User()
{
email = "email@hotmail.com",
password = "password123"
};
Token newToken = auth.Authenticate(u, ApiUrls.Signin).Result;
Console.Write("Content: " + newToken.user._id);
Console.Read();
}
}