.NET Core Web API 异步数据返回



我正在尝试以异步方式处理以GET HTTP响应将数据返回给APi客户端,但到目前为止没有运气。

我的代码 :

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

如您所见,我想通过返回所有用户和另一种方法通过其 ID 返回单个用户来异步处理 GET 请求。我不知道我是否需要ObjectResult类,但我需要使用 JSON 对象向客户端负责。有人知道如何做到这一点吗?

在这里,试试这个:

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

请注意,在GetUsers中,您必须返回IActionResult,而不是IAsyncResult