I am working on a web api and I need to be able to search a path with a DateTime and receive all books that contain that Date.
So for example /api/books/published/2012 returns all with 2012 in their date.
As well as api/books/published/2012/8/15 returns all with 2012-08-15 in their's.
I have tried
public ActionResult GetBooksSortedByDate()
{
if (!_bookList.Any())
return NotFound();
return Ok(_bookList);
}
[HttpGet("published/{published}")]
public IActionResult GetBookByDate(DateTime published)
{
var book = FindBookByDate(published);
if (book is null) return NotFound();
return Ok(book);
}
//returnerar böcker innehållandes sökt datum
private IEnumerable<Book> FindBookByDate(DateTime published)
{
return _bookList.Where(_bookList => _bookList.Publish_date.Equals(published));
}
Using /api/books/published/2012-8-15 in Postman gets me the book created then.
meanwhile /api/books/published/2012 does not give me any objects. And I know this is because I have set _booklist.Publish_date.Equals(published)); .
So what do I need to replace .Equals with to get something along the lines of a .Contains(Value)
And regarding double
I want to be able to do the following.
/api/books/price/30.0&35.0 returns all with price between '30.0' och '35.0'
Same situation here, I get results on /api/books/price/33.0 but I do not know how to do a price between 30.0 and 35.0.
My code looks like this. I believe I need to send in 2 doubles here for it to check both of them?
//Visar /price/value&value
[HttpGet("price/{price}&{price}")]
public IActionResult GetBooksByTwoPrices(double firstPrice, double secondPrice)
{
var book = FindBooksByTwoPrices(firstPrice,secondPrice);
if (book is null) return NotFound();
return Ok(book);
}
private IEnumerable<Book> FindBooksByTwoPrices(double firstPrice, double secondPrice)
{
var allBooksBetweenPrices = _bookList.Where(_bookList => _bookList.Price.Equals(firstPrice) && _bookList.Price.Equals(secondPrice);
return allBooksBetweenPrices;
//return _bookList.Where(_bookList => _bookList.Price.Equals(price));
}
I know my var allBooksBetweenPrices = ... does not work as it can't be 2 value's at once but I guess this is somewhat the way to approach it?
Worth to note... My Book.cs only contains public double price { get; set; } Do I need another one to check for the other price?
2012-8-15works as aDateTimeand2012not is because model binder tries to parse the route parameterstringtoDateTimeand2012is not a valid date time string. You can see for yourself usingDateTime.Parse()method. Also, are route-based parameters a requirement? If not, then I suggest accepting the parameters from query, that would make your life much easier, you could have multiple parameters for example. Read more about model binding in the docs.DateTime.Parse()?