我试图通过 Microsoft.Http 使用 API。我按照这里给出的样本 http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client , 但我的任务没有完成,一直在 WaitingForActivation 状态
登录按钮:
private void btnLogin_Click(object sender, EventArgs e) {
try {
var t = Api.LoginAsync( tbUsername.Text, tbPassword.Text);
t.Wait();
_Token = t.Result;
}
catch (Exception ex) {
ShowError(ex.Message);
}
}
API类
static class Api {
private const string URLBase = "http://localhost:28929/";
public static async Task<string> LoginAsync(string Username, string Password ) {
using (var client = new HttpClient()) {
client.BaseAddress = new Uri(URLBase);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var VM = new Usuario() { Username = Username, Password = Password};
HttpResponseMessage response = await client.PostAsJsonAsync("api/login", VM);
if (response.IsSuccessStatusCode) {
return await response.Content.ReadAsAsync<string>();
}
else {
throw new ApplicationException("No se pudo ingresar. Error: " + response.StatusCode.ToString());
}
}
}
}
最佳答案
您还需要使您的事件处理程序async
:
private async void btnLogin_Click(object sender, EventArgs e) {
try {
_Token = await Api.LoginAsync( tbUsername.Text, tbPassword.Text);
}
catch (Exception ex) {
ShowError(ex.Message);
}
}
关于c# - 任务一直在等待激活,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34551008/