Dear Deer
Dear Deer

Reputation: 543

.NET Core Web API async data return

I'm trying to handle returning data to APi client in GET HTTP response in asynchronous manner but with no luck so far.

My code :

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Server.Database;
using System;
using System.Threading.Tasks;

namespace Server.Controllers
{
    //[Produces("application/json")]
    [Route("api/[Controller]")]
    public class UserController : Controller
    {
        private readonly DBContext _context;

        public UserController(DBContext context)
        {
            _context = context;
        }

        [HttpGet("/Users")]
        public async Task<IAsyncResult> GetUsers()
        {
            using (_context)
            {
                // how to properly return data asynchronously ? 
                var col = await _context.Users.ToListAsync();
            }
        }

        [HttpGet("/Users/{id}")]
        public async Task<IActionResult> GetUserByID(Int32 id)
        {

            using (_context)
            {
                //this is wrong, I don't knwo how to do it properly
                //var item = await new ObjectResult(_context.Users.FirstOrDefault(user => user.IDUser == id));
            }
        }
    }
}

As you can see I would like to handle GET request asynchronously by returning all users and in another method single user by his ID. I don't know if I need ObjectResultclass as well but I need to respons with JSON object to the client. Someone know how to do this ?

Upvotes: 4

Views: 9240

Answers (1)

Yurii N.
Yurii N.

Reputation: 5703

Here, try this:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Server.Database;
using System;
using System.Threading.Tasks;

namespace Server.Controllers
{
    //[Produces("application/json")]
    [Route("api/[Controller]")]
    public class UserController : Controller
    {
        private readonly DBContext _context;

        public UserController(DBContext context)
        {
            _context = context;
        }

        [HttpGet("/Users")]
        public async Task<IActionResult> GetUsers()
        {
            return Json(await _context.Users.ToListAsync());            
        }

        [HttpGet("/Users/{id}")]
        public async Task<IActionResult> GetUserByID(Int32 id)
        {
            return Json(await new _context.Users.FirstOrDefault(user => user.IDUser == id));          
        }
    }
}

Note, that in GetUsers you must return IActionResult, not IAsyncResult.

Upvotes: 3

Related Questions