如何使用异步任务获取数据并显示在视图中?
How to use async Task to get data and show in a view?
我有一个网络 API 我想在控制器中获取一些数据并显示在视图上。
这是我的主class:
public class APISrv
{
public string result = string.Empty;
public async Task<string> GetIT()
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:2474/");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await
client.GetAsync("api/Test/Get");
if (Res.IsSuccessStatusCode)
{
result = Res.Content.ReadAsStringAsync().Result;
}
}
}
catch (Exception err)
{
result=err.Message;
}
return result;
}
}
我用两个控制器测试了我的class:
一个:
public ActionResult Index()
{
APISrv aPISrv = new APISrv();
aPISrv.GetIT();
ViewData["mydata"] = aPISrv.result;
return View();
}
在这个原因中 "result" 是一个 public 字段并且总是空的,似乎主线程不等待异步方法完成它的 work.i 可以看到我的视图但是 "ViewData["mydata"]" 为空。
秒:
public ActionResult Index()
{
APISrv aPISrv = new APISrv();
ViewData["mydata"] = aPISrv.GetIT().Result;
return View();
}
这会导致我的页面停留在 "waiting for local..." 模式,无法正常工作。
我怎样才能从我的 class 获取数据?
您将阻塞调用 (.Result
) 与 async/await
混合使用,这可能会导致死锁。这就是您在调用控制器操作时没有得到结果的原因。
引用Async/Await - Best Practices in Asynchronous Programming
要么一路异步,要么一路同步。尽量不要混用。
result = await Res.Content.ReadAsStringAsync();
同时将操作更新为异步
public async Task<ActionResult> Index() {
var aPISrv = new APISrv();
ViewData["mydata"] = await aPISrv.GetIT();
return View();
}
此外,该服务应该被抽象出来并通过构造函数注入进行注入,但这超出了这个问题的范围。
我有一个网络 API 我想在控制器中获取一些数据并显示在视图上。
这是我的主class:
public class APISrv
{
public string result = string.Empty;
public async Task<string> GetIT()
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:2474/");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await
client.GetAsync("api/Test/Get");
if (Res.IsSuccessStatusCode)
{
result = Res.Content.ReadAsStringAsync().Result;
}
}
}
catch (Exception err)
{
result=err.Message;
}
return result;
}
}
我用两个控制器测试了我的class:
一个:
public ActionResult Index()
{
APISrv aPISrv = new APISrv();
aPISrv.GetIT();
ViewData["mydata"] = aPISrv.result;
return View();
}
在这个原因中 "result" 是一个 public 字段并且总是空的,似乎主线程不等待异步方法完成它的 work.i 可以看到我的视图但是 "ViewData["mydata"]" 为空。
秒:
public ActionResult Index()
{
APISrv aPISrv = new APISrv();
ViewData["mydata"] = aPISrv.GetIT().Result;
return View();
}
这会导致我的页面停留在 "waiting for local..." 模式,无法正常工作。
我怎样才能从我的 class 获取数据?
您将阻塞调用 (.Result
) 与 async/await
混合使用,这可能会导致死锁。这就是您在调用控制器操作时没有得到结果的原因。
引用Async/Await - Best Practices in Asynchronous Programming
要么一路异步,要么一路同步。尽量不要混用。
result = await Res.Content.ReadAsStringAsync();
同时将操作更新为异步
public async Task<ActionResult> Index() {
var aPISrv = new APISrv();
ViewData["mydata"] = await aPISrv.GetIT();
return View();
}
此外,该服务应该被抽象出来并通过构造函数注入进行注入,但这超出了这个问题的范围。