0

Is there a way to use domain objects as API GET route parameters?

My reason is, I have an API action like this:

public async Task<IActionResult> CancelOnlineMeeting(string id)

I'd like to the api to parse the incoming string into an id object like this:

    public class Id
    {
        public string Value { get; }

        public Id(string value)
        {
            //example logic
            if(string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException("value");
            }

            if(value.Length > 10)
            {
                throw new ValidationException("Invalid length");
            }


            Value = value.Trim();
        }
    }

And then use the route:

public async Task<IActionResult> CancelOnlineMeeting(Id id)

The benefit would be to validate the Id object value in one place, when using the Id object in multiple actions.

Sam Jones
  • 4,443
  • 2
  • 40
  • 45
  • 1
    https://learn.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding?view=aspnetcore-7.0 – CodeCaster Mar 14 '23 at 11:11
  • 1
    Don't do modelvalidation yourself and definetly not in the constructor of that class. Binding works differently. You may simply use the Id class there but just put a Required attribute on the property and give it a setter so serializing into it works. Then Name that property like its called in the route and add a FromRoute Attribute to the class in the endpoints method signature. – Ralf Mar 14 '23 at 13:20
  • @CodeCaster, if you add your comment as an answer i'll accept it. – Sam Jones Mar 14 '23 at 17:34
  • @Ralf, thanks for the feedback, i'll bare this in mind. I've been using string ids and email addresses as parameters and i've got "primitive obsession" repeating in my head so looking at alternatives. – Sam Jones Mar 14 '23 at 17:36

0 Answers0