can not use await in .net core web api?

mc 3,641 Reputation points
2023-05-23T05:45:48.11+00:00

If I use var result=query.ToList();

it is ok

If I use var result =await query.ToListAsync();

there will be error :

An error occurred using the connection to database on server System.Threading.Tasks.TaskCanceledException

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,157 questions
{count} votes

3 answers

Sort by: Most helpful
  1. simone cammarano 30 Reputation points
    2023-05-23T06:36:04.84+00:00

    Probably you are inside a Background Task.

    Remember that if all Foreground Task end, all background task will be killed.

    0 comments No comments

  2. mc 3,641 Reputation points
    2023-05-23T09:01:25.8166667+00:00

    @Zhi Lv - MSFT I find the problem it was a requestFilter I add in Program.cs

    public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
    
    next();
    
                    return Task.CompletedTask;
    }
    

    I remove the filter it is ok but I add the filter is is not ok.

    0 comments No comments

  3. Rijwan Ansari 746 Reputation points MVP
    2023-05-23T13:06:26.0733333+00:00

    Hi,

    You can do that, however your method should be async Task as shown:

    public async Task<List<customer>> GetDotNetCount()
    {
      var customers = await cuatomerQuery.ToListAsync();
      return customers;
    }
    
    
    0 comments No comments