0

Building an ASP.Net Core 5.0 service. In order to make this service mirror our other APIs I want to:

Have a route that supports the following URIs

// returns a single item
/api/Items/{id}

// returns multiple items
/api/Items/?date={date}

In the above, {id} could be an int, or a guid, and date is in the format YYYYMMDD

Couple

[ApiController]
[Route("Items")]
public class ItemController: ControllerBase
{
    [HttpGet("{id}")]
    public Item Get(string id)
    {
    }

    [HttpGet()]
    public IEnumerable<Item> Get([FromQuery] DateTime date)
    {
       return new List<Item> { new Item() };
    }
}

When I run this, which I'm debugging using the Swagger functionality, it appears that I get two methods:

/Items/{id}
/Items/?date={date}

So far so good, except, that I want to support date strings of YYYYMMDD, but the default date converter does not support that.

One kludge is to make this a string and convert in the function(boo). Ideally, I'd like to register an additional Date parser for all endpoints.

Ideas?

Xerillio
  • 4,855
  • 1
  • 17
  • 28
bpeikes
  • 3,495
  • 9
  • 42
  • 80
  • Please read through your question at least once before posting. The formatting is messed up, you write "YYYYMMDD" in one place "YYYY-MM-YY" in another, the code block has left half the code outside. It's pretty lazy and gives a bad impression considering you have 2626 rep. On another note: what exactly is the question? Are you getting an error when using the date format? Or are you asking about how to set up input validation to **only** allow a certain format? – Xerillio May 06 '21 at 18:42
  • It was a typo, which I fixed. I’m looking for a way to accept date formats of YYYYMMDD as well as the standard supported ones. – bpeikes May 06 '21 at 19:29
  • It's still not clear how you current solution does not accept/support that format. How is it behaving differently than you expect? Have you tried one of the solutions [found here](https://stackoverflow.com/questions/41642800/change-default-format-for-datetime-parsing-in-asp-net-core)? Why not use the [ISO standard format](https://www.iso.org/iso-8601-date-and-time-format.html)? – Xerillio May 06 '21 at 20:18
  • So why don't you use the string type to accept, and then make a quasi-change? – Yinqiu May 07 '21 at 01:52
  • @Xerillio - As stated in the OP, I want to support the YYYYMMDD format because other APIs in my organization use that format. I want to be consistent with them. I will try the TypeConverter code found half way down in the article you posted. Thanks. If it works, I'll add it as an answer here. – bpeikes May 07 '21 at 02:32

0 Answers0