简体   繁体   English

.Net Core Web API 响应具有多个属性

[英].Net Core Web API response with multiple properties

I am designing an API endpoint and planning to send the response with 2 values ( one with total no of records and second with list of records ) The controller action is designed like below我正在设计一个 API 端点并计划发送带有 2 个值的响应(一个带有总记录数,第二个带有记录列表) controller 操作的设计如下

    [HttpGet]
    [Route("users_bycat")]
    public async Task<ActionResult> GetUsersByCat([FromQuery] int categoryId )
    {       
        var query = db_context.Users.Select(a => a).Where(p => p.CategoryId == categoryId);                   
        var result = await query.ExecuteAsync();

        return Ok(
               new
               {
                   totalRecords = result.Count(),
                   users = result.ToList()
               }
            );
    }

When i am calling this api endpoint, i am getting response like below当我调用这个 api 端点时,我得到如下响应

    {
        "totalRecords": 37652,
        "users": []
    }

The users array is empty and i try like below, and managed to get the list as response, but i would like to add count as well to the response用户数组是空的,我尝试如下所示,并设法将列表作为响应,但我也想在响应中添加计数

    return Ok(  result.ToList());

How can i ensure i will get both totalRecords and users List as a part of response我如何确保我将同时获得 totalRecords 和 users List 作为响应的一部分

The ExecuteAsync() is redundant as an IQueryable is materialised upon calling .ToList() . ExecuteAsync()是多余的,因为IQueryable在调用.ToList()时实现。 Additionally, calling .Count() will execute an additional database query so it's more efficient to move this call onto the List .此外,调用.Count()将执行额外的数据库查询,因此将此调用移至List会更有效。 The exception to this would be if you were implementing paging.如果您正在实现分页,则例外。

The below should function as required:以下应根据需要 function:

[HttpGet]
[Route("users_bycat")]
public async Task<ActionResult> GetUsersByCat([FromQuery] int categoryId )
{       
    var results = await db_context.Users
      .Where(p => p.CategoryId == categoryId)
      .ToListAsync();
    
    var dto = new
    {
      totalRecords = results.Count,
      users = results
    };

    return Ok(dto);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM