简体   繁体   English

在 ASP.NET Core Web API 中使用一些查询和可排序字段获取请求的最佳实践

[英]Best practice for get request with some query and sortable fields in ASP.NET Core Web API

I have this action in CommodityTypeController :我在CommodityTypeController有这个动作:

[HttpGet("")]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<ActionResult> Get(string name, int page = 1, int count = 10)
{
    var result = await commodityTypeService.Get(name: name, page, count);
    return Ok(result);
}

which returns a list of CommodityTypeDto .它返回CommodityTypeDto的列表。

This is my CommodityTypeService :这是我的CommodityTypeService

public async Task<IEnumerable<CommodityTypeDto>> Get(string name,int page, int count)
{
    var entities = await commodityTypeRepository.Get(x => name.HasValue() ? x.Name.Contains(name) : true, page, count);
    var dtos = mapper.Map<IEnumerable<CommodityTypeDto>>(entities);
    return dtos;
}

And this is my CommodityTypeDto :这是我的CommodityTypeDto

public class CommodityTypeDto
{
    public long Id { get; set; }
    public string Name { get; set; }
    public decimal AccountNumberId { get; set; }
}

And finally, this is my CommodityTypeRepository :最后,这是我的CommodityTypeRepository

public async virtual Task<IEnumerable<CommodityType>> Get(Expression<Func<CommodityType, bool>> expression, int page, int count)
{
    var result = await set.Where(expression)
                          .Skip((page-1) * count)
                          .Take(count)
                          .ToListAsync();
    return result;
}

What is best practice for create a get api?创建 get api 的最佳实践是什么? If I want to search with more parameters and sort per some field in my API, is this a good method?如果我想在我的 API 中使用更多参数进行搜索并按某个字段进行排序,这是一个好方法吗?

Is there any library for sorting and querying from an API to an EF context?是否有任何库用于从 API 到 EF 上下文进行排序和查询?

On the back end You should apply filtering to minimize the traffic from server to the client.在后端您应该应用过滤以最小化从服务器到客户端的流量。 On the front end You should apply sorting and filtering over returned results.在前端您应该对返回的结果应用排序和过滤。 Imagine the situation when you want to sort a really big amount of data on the back end.想象一下当您想在后端对大量数据进行排序时的情况。 For every change of the sorting criteria the same amount of data will be transferred.对于排序标准的每次更改,将传输相同数量的数据。

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

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