从 Web API 操作方法调用异步方法

Sam*_*Sam 0 c# asp.net-mvc asp.net-web-api2

我正在从我的 Web API 操作方法中调用一个异步方法,它看起来像这样,但我收到“无法将类型任务员工隐式转换为员工”错误。

我需要做什么?

我的 Web API 操作方法如下所示:

public IHttpActionResult GetEmployee()
{

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

   return Ok(emp);
}
Run Code Online (Sandbox Code Playgroud)

我调用的方法如下所示:

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

   // Some logic here to retrieve employee info

   return employee;
}
Run Code Online (Sandbox Code Playgroud)

我需要做什么才能调用此方法来检索员工信息?

PS GetSomeEmployee() 方法必须是异步的,因为它会进行其他异步调用来检索员工数据。

Pet*_*iho 5

您需要同步调用该方法,或者使用await. 例如:

同步(GetEmployee()将阻塞直到GetSomeEmployee()完成):

public IHttpActionResult GetEmployee()
{

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

   return Ok(emp);
}
Run Code Online (Sandbox Code Playgroud)

异步(GetEmployee()会立即返回,GetSomeEmployee()完成后继续):

public async Task<IHttpActionResult> GetEmployee()
{

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

   return Ok(emp);
}
Run Code Online (Sandbox Code Playgroud)