【问题标题】:.NET Core Web API async data return.NET Core Web API 异步数据返回
【发布时间】:2017-12-11 13:53:12
【问题描述】:

我正在尝试以异步方式在 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 请求。我不知道我是否也需要ObjectResultclass,但我需要用 JSON 对象响应客户端。有人知道怎么做吗?

【问题讨论】:

  • 首先using DbContext是个坏主意,最好注册到Startup,其次,尝试返回Json,像这样:return Json(await _context.Users.ToListAsync());
  • 感谢@Yuriy N 的回答。Json(await _context.Users.ToListAsync()) 的问题是我有Cannot implicitly convert type 'Microsoft.AspNetCore.Mvc.JsonResult' to 'System.IAsyncResult' 错误。
  • 我已经回答了这个问题。

标签: asynchronous asp.net-core-mvc asp.net-core-webapi


【解决方案1】:

在这里,试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多