Web API Binds Immutable Models

In our code base, DTOs are immutable types with readonly, getters for state fields and a constructor that takes values, so the type of a hypothetical person looks like this:

public class Person
    {
        private readonly String _firstName;
        private readonly String _secondName;

        public Person(String firstName, String secondName)
        {
            _firstName = firstName;
            _secondName = secondName;
        }

        public String FirstName
        {
            get { return _firstName; }
        }

        public String SecondName
        {
            get { return _secondName; }
        }
    }

Using the Web API, is it possible to bind such a model without exposing public setters to properties?

+4
source share
2 answers

YES, POSSIBLE to bind this without publicly available properties. By default, you will need a public setter for this. However, if you have a constructor that initializes and is standard, the infrastructure can construct objects.

, , , (FirstName LastName), .

- - Json. , JsonConstructor, , , .

+8

, , WebAPI, :

public class PersonRequestModel
{
    public String FirstName { get; set; }
    public String SecondName { get; set; }

    public static implicit operator Person(PersonRequestModel request) {
        return new Person(request.FirstName, request.SecondName);
    }
}

public class Person
{
   private readonly String _firstName;
   private readonly String _secondName;

   public Person(String firstName, String secondName)
   {
       _firstName = firstName;
       _secondName = secondName;
   }

   public String FirstName
   {
       get { return _firstName; }
   }

   public String SecondName
   {
       get { return _secondName; }
   }
}
+2

All Articles