因此,我正在创建一个数据库,允许用户创建“神奇项目”,然后将其上传到我的 ASP.net Web API。这很好用。我想通过从 api 中提取所有这些项目来在我的网页中显示它们。这也很好用。但现在,当我尝试过滤、排序或限制搜索量时,我仍然可以获得返回给我的每个项目的基本列表。现在,只有 14 个条目,所以没什么大不了的,但我仍然想完成这个。但无论我做什么,它总是返回完整的列表。
这是 Visual Studio 中的 ASP.net Controller :
[Route("api/v1/MagicItem")]
public class MagicItemController : Controller
{
private ItemListContext context;
public MagicItemController(ItemListContext context)
{
this.context = context;
}
[Produces("application/json")]
[HttpGet]
//public List<MagicItem> GetAllItems(string name, string category, string rarity, int? page, string sort, int limit = 5, string dir = "desc")
public List<MagicItem> GetAllItems(
string name,
string category,
string rarity,
int? page,
string sort,
int limit = 5,
string dir = "desc")
{
IQueryable<MagicItem> query = context.MagicItems;
if (!string.IsNullOrWhiteSpace(name))
query = query.Where(d => d.Name.Contains(name));
if (!string.IsNullOrWhiteSpace(category))
query = query.Where(d => d.Category == category);
if (!string.IsNullOrWhiteSpace(rarity))
query = query.Where(d => d.Rarity == rarity);
if (!string.IsNullOrWhiteSpace(sort))
{
switch (sort)
{
case "Name":
if (dir == "asc")
query = query.OrderBy(d => d.Name);
else if (dir == "desc")
query = query.OrderByDescending(d => d.Name);
break;
case "Rarity":
if (dir == "asc")
query = query.OrderBy(d => d.Rarity);
else if (dir == "desc")
query = query.OrderByDescending(d => d.Rarity);
break;
case "Category":
if (dir == "asc")
query = query.OrderBy(d => d.Category);
else if (dir == "desc")
query = query.OrderByDescending(d => d.Category);
break;
}
}
query = query.Take(limit);
if (page.HasValue)
query = query.Skip(page.Value * limit);
return context.MagicItems.ToList();
}
}
最佳答案
你就快到了:
只需使用:
return query.ToList();
而不是:
return context.MagicItems.ToList();
关于c# - ASP.NET Core Web API 中的过滤结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50657614/