【问题标题】:Find specific item on icollection在 collection 上查找特定项目
【发布时间】:2018-10-05 10:53:37
【问题描述】:

我正在开发一个 web api,并尝试通过 icollection 的名称查找产品,特别是与给定名称 (?name={name}) 匹配的产品。

目前我有这个:

[HttpGet("name", Name = "GetProductByName")]
public ActionResult<Product> GetByName(string _name)
{
    var prod = (from x in _context.Products 
                where x.Name == _name 
                select x).FirstOrDefault();

    if (prod == null)
    {
        return NotFound();
    }
    return prod;
}

但每当我查询 api (api/product/?name={name}) 时,我都会得到所有结果

我做错了什么?

编辑:控制器的其余部分,因为它不是参数不匹配。我正在使用 EF DbSet

[Route("api/Product")]
[ApiController]
public class ProductController : ControllerBase
{
    private readonly OrderingProductsContext _context;

    public ProductController(OrderingProductsContext context)
    {
        _context = context;
    }


    [HttpGet]
    public ActionResult<List<Product>> GetAll()
    {
        return _context.Products.ToList();
    }


    [HttpGet("{id}", Name = "GetProduct")]
    public ActionResult<Product> GetById(long id)
    {
        var prod = _context.Products.Find(id);
        if (prod == null)
        {
            return NotFound();
        }
        return prod;
    }


    [HttpPost]
    public IActionResult Create(Product prod)
    {
        _context.Products.Add(prod);
        _context.SaveChanges();

        return CreatedAtRoute("GetProduct", new { id = prod.ID }, prod);
    }

【问题讨论】:

  • 可以分享整个控制器吗?您可能有另一个端点来完成 api/product/?name={name} 查询。
  • 您的参数是“_name”而不是“name”,我可以看到!
  • 这里没有ICollection_context 很可能是 EF DbContext。这将生成一个数据库查询。这段代码甚至不应该编译
  • 编辑了我的问题并发布了整个控制器,因为参数不匹配并没有解决问题。
  • @idetodospoca 我建议你在 GetAll() 方法中放置一个断点。我很确定您向该方法发出请求,但不是 GetByName。此外,您的 GetByName 属性缺少大括号。它应该像 [HttpGet("{name}"...

标签: c# asp.net linq icollection


【解决方案1】:

您将_name 作为参数,但使用name 检查您的情况

改变

var prod = (from x in _context.Products where x.Name == name select x).FirstOrDefault();

var prod = (from x in _context.Products where x.Name == _name select x).FirstOrDefault();

【讨论】:

    【解决方案2】:

    您应该在方法定义中将_name 替换为name。根据您发布的代码,很明显where 子句没有使用在每次调用GetByName 时传递的参数,而是使用了变量name 的值。

    【讨论】:

      【解决方案3】:

      首先,您应该在属性参数中使用大括号;

      [HttpGet("{name}", Name = "GetProductByName")]
      

      然后你可以用 this 调用那个端点;

       api/product/GetProductByName/{name}
      

      或者,如果您想使用查询字符串进行调用,您可以使用;

      [HttpGet(Name = "GetProductByName")]
      public ActionResult<Product> GetByName([FromQuery]string name)
      

      并要求类似;

      api/product/GetProductByName?name={name}
      

      【讨论】:

        猜你喜欢
        • 2016-03-23
        • 1970-01-01
        • 2021-10-02
        • 2021-09-24
        • 2010-11-12
        • 1970-01-01
        • 2021-11-24
        • 2015-07-17
        • 1970-01-01
        相关资源
        最近更新 更多