Web api 具有多个路由 controller/{path}&{path}

Web api with multiple routes controller/{path}&{path}

我正在尝试创建一个 Web api,它允许我获取价格介于两个不同值之间的所有书籍。

因此,通过输入 api/books/price/30.0&35.0,我将 return 所有书籍 with price between '30.0' och '35.0' sorted by price。我的代码如下所示。

[HttpGet("price")]
    public ActionResult GetBooksSortedByPrice()
    {
        var book = FindBooksSortedByPrice();
        if (book is null) return NotFound();
        return Ok(book);
    }
    [HttpGet("price/{price}")]
    public IActionResult GetBookByPrice(double price)
    {
        var book = FindBookByPrice(price);
        if (book is null) return NotFound();
        return Ok(book);
    }
    //returns books from requested price
    private IEnumerable<Book> FindBookByPrice(double price)
    {
        //var allBooksBetweenPrices = _bookList.Where(_bookList => (_bookList.Price >= firstPrice) && (_bookList.Price <= secondPrice));
        //return allBooksBetweenPrices;
        return _bookList.Where(_bookList => _bookList.Price.Equals(price));
    }
    private IEnumerable<Book> FindBooksSortedByPrice()
    {
        return _bookList.OrderBy(b => b.Price).Where(_bookList => _bookList.Price.Equals(_bookList.Price));

    }

我知道我可能会被告知我的路由可能会更好,但由于我不理解该指南,所以我已经完整阅读了我很高兴收到更简短的解释(带有代码示例)。

我建议您使用 2 个价格输入参数而不是一个


[Route("price/{minprice}/{maxprice}")]
public ActionResult<IEnumerable<Book>> GetBooksSortedByPrice(double minPrice, double maxPrice)
    {
        var books = FindBooksSortedByPrice(minPrice, double maxPrice);
        if (books== null) return NotFound();
        return Ok(books);
    }

[NonAction]
 private IEnumerable<Book> FindBookByPrice(ddouble minPrice, double maxPrice)
    {
  return _bookList
.Where(b => (b.Price >= minPrice) && (b.Price <= maxPrice))
.OrderBy(o=>o.Price)
.ToArray();
        
    }