控制器中的方法在httpClient处停止.SendAsync(请求);ASP.NET



我正试图从网页调用控制器中的一个方法。但是,当代码运行时,它将停止在httpClient上执行。SendAsync(请求(;。永远不要超越这一点。它在.net控制台应用程序中运行良好,但在ASP。NET web应用程序。

这是我的方法:

public static async Task<Employee> LoadData(int ID)
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.example.net/api/GetData"))
{
request.Headers.TryAddWithoutValidation("Authorization", "Basic TOKEN HERE");
var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
JObject o = JObject.Parse(responseBody);
JToken t = o.SelectToken("$.value[?(@.Id == " + "'" + ID + "'" + ")]");
string a = t.ToString();
Employee e = JsonConvert.DeserializeObject<Employee>(a);

return e;
}
}
}

这是控制器的方法:

public JsonResult Test()
{
try
{
Api.LoadData(507);
return Json(true, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}

感谢您的帮助。

这里有两个选项:

使用Task.GetAwaiter()等待LoadData完成,然后返回值。(警告:它正在调用异步LoadData并同步阻止它,因此它根本不是异步的,也可能导致死锁。(

public JsonResult Test()
{
try
{
Api.LoadData(507).GetAwaiter().GetResult();
return Json(true, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}

或者您可以将Test()方法更改为async:

public async JsonResult Test()
{
//...
}

最新更新