【发布时间】: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