Skip to main content
edited tags
Link
Peter Csala
  • 10.8k
  • 1
  • 16
  • 36
Source Link
t3chb0t
  • 44.7k
  • 9
  • 85
  • 191

Action argument supporting multiple units as string

I've got a controller with two actions that need to support two units: hours & times. The url should read like this:

api/workflows/active/next/hour
api/workflows/active/next/time
api/workflows/active/next/3/hours
api/workflows/active/next/3/times

In order to not write any extra validation for the unit parameter I have defined the last route segment as regex:

[HttpGet("active/next/{unit:regex(^(hour|time))}")]
public async Task<IActionResult> GetNextSingle(string unit)
{
    return await GetNextMany(1, $"{unit}s");
}

[HttpGet("active/next/{value:int:min(1):max(10)}/{unit:regex(^(hours|times))}")]
public async Task<IActionResult> GetNextMany(int value, string unit)
{
    return Ok(new { value, unit });              
}

Would say this is how it's usually done or are there other smarter ways?