Sam
Sam

Reputation: 30388

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?

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

Upvotes: 0

Views: 4759

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70652

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

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);
}

Upvotes: 5

Related Questions