Skip to content

How to implement an async controller in MVC 6? #767

@tinganho

Description

@tinganho

I have searched for 2 hours and couldn't find an async example of how to implement an async controller in MVC 6. All examples seem to sync controllers.

What I want to achieve is something like below. But it doesn't work:

[Route("api/[controller]")]
    public class MediaController
    {
         [HttpGet]
         public async Task<MediaList> Get()
         {
             Media media1 = new Media(DbContext) { Id = 1, Title = "Hello world" };
             DbContext.Medias.Add(media1);
             Media media2 = new Media(DbContext) { Id = 2, Title = "Hello world" };
             DbContext.Medias.Add(media2);

             var mediaList = await DbContext.Medias
                 .OrderByDescending(m => m.Id)
                 .Take(10)
                 .ToListAsync();

            return mediaList;
        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions