How mark a .NET Web API Regex Route Parameter as optional

130 views Asked by At

Microsoft explains that you can do optional attribute routing here: Optional Attribute Routing for Web API 2, simply by adding a '?' to the end of the parameter.

I have a regex parameter, but I am having trouble setting the parameter as optional. The regex works fine, but as soon as I start trying to work out how to mark it as optional, the constraint resolver chokes.

[Route(@"{id:long}/terminate/{terminationDate:regex('^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$)}")]

Removing the string literal allows the optional but seems to break the regex:

[Route("{id:long}/terminate/{terminationDate:regex('^(19|20)\\d\\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$)?}")]

More plainly I want to achieve:

/123456/terminate/2021-11-12

OR

/123456/terminate/

Am I just trying to escape this incorrectly?

0

There are 0 answers