I'm trying to determine if it's possible to have an optional section of a string in a given route URL using C# and ASP.NET MVC 5.
For example:
[HttpGet]
[Route("~/hot-dogs{withMustard:regex(-with-mustard?)}/", Name = "HotDogOrder")]
public async Task<ActionResult> HotDogOrder(string withMustard= null)
I want the route to work for either:
https://www.domain.tld/hot-dogs/
https://www.domain.tld/hot-dogs-with-mustard/
If I use that regular expression, it will match for https://www.domain.tld/hot-dogs-with-mustard/
, but not https://www.domain.tld/hot-dogs/
I don't want to add the with-mustard
as what would look like a subdirectory such as:
https://www.domain.tld/hot-dogs/with-mustard/
Is this even possible? I've tried using an optional ?
, *
, but can't seem to get this to work. I want to use the Route
decorators and not have to create different functions for every single option that could be possible.
Any ideas, or is this not possible?
I've tried various regex values and can't seem to find something that will work for both use cases
You could use two routes and check for the Path property.
I don't think regex is thinked to work on entire routing, it works on single parameter.
[HttpGet]
[Route("hot-dogs")]
[Route("hot-dogs-with-mustard")]
public ActionResult<string> DoSomething() {
var path = Request.Path; //
}
Try also this, works also with something like hot-dogs-with-mustard-ketchup
[HttpGet]
[Route("hot-dogs")]
[Route("hot-dogs{actionPath:regex(^(-with(-(ketchup|mustard|relish))+)$)}")]
public ActionResult<string> DoSomething(string? actionPath) {
return Ok(actionPath);
}