簡體   English   中英

使用異步調用Web api的異步方法被卡住,並且沒有返回給調用者

[英]Async method called to the web api with async is stuck and not returning to the caller

我想通過C#Task調用Web API,但是我無法獲得返回的結果,盡管它確實跳轉到了我指出的獲取值的URL。

我會錯誤地實現異步和等待方法嗎?

下面是我的代碼:

  • 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返回到調用方?

任何幫助將非常感激。

謝謝

不要阻塞async代碼; 一路使用async

public async Task<ActionResult> Index()
{
  await Developer();

  return View();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM