简体   繁体   中英

Calling an async method from Web API action method

I'm calling an async method from my Web API action method that looks like this but I'm getting "Cannot implicitly convert type Task Employee to Employee" error.

What do I need to do?

My Web API action method looks like this:

public IHttpActionResult GetEmployee()
{

   // Get employee info
   Employee emp = myDataMethod.GetSomeEmployee();

   return Ok(emp);
}

And the method I'm calling looks like this:

public static async Task<Employee> GetSomeEmployee()
{
   Employee employee = new Employee();

   // Some logic here to retrieve employee info

   return employee;
}

What do I need to do so that I can call this method to retrieve employee information?

PS The GetSomeEmployee() method has to be async because it makes other async calls to retrieve employee data.

You need to either call the method synchronously, or use await . Eg:

Synchronously ( GetEmployee() will block until GetSomeEmployee() completes):

public IHttpActionResult GetEmployee()
{

   // Get employee info
   Employee emp = myDataMethod.GetSomeEmployee().Result;

   return Ok(emp);
}

Asynchronously ( GetEmployee() will return immediately, and then be continued when GetSomeEmployee() completes):

public async Task<IHttpActionResult> GetEmployee()
{

   // Get employee info
   Employee emp = await myDataMethod.GetSomeEmployee();

   return Ok(emp);
}

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