I have a simple controller which allows a route path constrained by a regex pattern in a 'complex object'. When I try to read the single property from the object it is always null.
The ModelState
is showing an errors collection saying:
The ActorId field is required
So it appears to be a model binding issue and not a validation issue.
I feel like I'm missing a pattern in the [HttpGet]
block or something.
ActorIdParameter.cs
public sealed class ActorIdParameter
{
[Required]
[RegularExpression(@"^.*nm(\d{5}|\d{7})$")]
public string ActorId { get; set; }
}
ActorsController.cs
[HttpGet("{actorIdParameter}")]
public async Task<IActionResult> GetActorByIdAsync([FromRoute]ActorIdParameter actorIdParameter)
{
_ = actorIdParameter ?? throw new ArgumentNullException(nameof(actorIdParameter));
// validation result
if (!ModelState.IsValid) //<---this is always false
return ValidationProcessor.GetAndLogInvalidActorIdParameter(method, logger);
}
Code is called using this example: http://localhost:4120/api/actors/nm0000206
There are several other posts which deal with the [FromQuery]
and [FromBody]
but I can't find anything that deals with the route path. It seems like the {actorIdParameter}
needs something to say "get the ActorId property within that object" or something.
I feel like I need the complex object for the regex matching. Alternatively I could switch from the ActorIdParameter
object to a string
and possibly decorate it inline on the GetActorByIdAsync
method but I'm curious if anyone has any suggestions?