【发布时间】:2019-08-29 18:29:04
【问题描述】:
我想通过 C# Task 调用 Web API,但我无法获得返回的结果,尽管它确实会跳转到我指出的 URL 以获取值。
我是否错误地实现了 async 和 await 方法?
下面是我的代码:
-
路由前缀为:
的Web API[RoutePrefix("api/values")] -
Web API 内部的方法如下:
[Route("Developer")] [HttpGet] public Task<List<string>> Developer() { var developer = new List<string> { "Developer", "Developer" }; return Task.FromResult(developer); } -
控制器
private async Task<List<string>> Developer() { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:52717/"); var response = await client.GetAsync("api/values/Developer"); if (response.IsSuccessStatusCode) return new List<string>(); throw new Exception("Unable to get the values"); } } public ActionResult Index() { Task.WaitAll(Developer()); return View(); }
每当我启动浏览器时,它都会进入 Index(),然后进入 Developer(),但是,它一直卡住并一直加载,直到 var response = await client.GetAsync("api/values/Developer") 被调用并一直运行到return Task.FromResult(developer);,一直卡在加载中。
有人知道如何让 Web API 回到调用者那里吗?
任何帮助将不胜感激。
谢谢
【问题讨论】:
-
如果不是设置基地址而是对整个 url 执行 getasync,您会看到不同的行为吗?
-
嗨@BugFinder,我已经尝试将整个URL放入
GetAsync方法和Uri方法中,但没有任何区别。 -
是的,您错误地使用了
async:Task.WaitAll阻塞了您的请求线程。
标签: c# multithreading asp.net-web-api