我正在尝试以异步方式处理向API客户端返回GET HTTP响应中的数据,但迄今为止没有成功。
我的代码:
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));
}
}
}
}
如您所见,我想通过返回所有用户和另一个方法的单个用户来异步处理GET请求。 我不知道是否需要 ObjectResult
类,但我需要向客户端响应JSON对象。 有人知道如何做到这一点吗?
您可以看到,我想通过返回所有用户和另一个方法的单个用户来异步处理GET请求。我不确定是否需要使用ObjectResult类,但是我需要向客户端返回JSON对象。请问有谁知道如何实现这一点吗?
DbContext
是一个不好的主意,最好在Startup
中注册它。其次,尝试返回Json
,类似这样:return Json(await _context.Users.ToListAsync());
- Yurii N.Json(await _context.Users.ToListAsync())
的问题在于我遇到了无法隐式转换类型'Microsoft.AspNetCore.Mvc.JsonResult'为'System.IAsyncResult'
的错误。 - Dear Deer