简体   繁体   中英

WEB API call stops working after introducing the “await” keyword

I have a simple web api method which retrieves a list of items from a database. When the method looks like this it works and the items are displayed in the UI:

[ActionName("GetServices")]
public async Task<IHttpActionResult> GetServices()
{
    var services = dbContext.Service.ToListAsync();
    return Ok(services);
}

But as soon as I introduce the await keyword to the method it stops working(if i put a break point on the method it still gets hit but nothing is displayed on the UI):

[ActionName("GetServices")]
public async Task<IHttpActionResult> GetServices()
{
    var services = await dbContext.Service.ToListAsync();
    return Ok(services);
}

"await" essentially means that you are making the runtime to wait until the method is executed. The first code snippet returns a task object while the second returns the actual services from db. Since you are saying that with first code block it displays the services you must be awaiting that task object in your UI layer. You must change your UI layer code after you put await in the WEB API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM