Reputation: 77
I am trying to bind only a subset of a class's properties from an API request body, I am unsure how to achieve this. If I could bind to a base class with only the properties I want to accept as input then cast it to the child class with the extra properties it would solve my problem but without serializing/deserializing that's not an option (i.e. can't cast from base to child). Example class, I only want to allow name to be bind from [FromBody]
public class project {
public string id { get; set; }
public string name { get; set; }
}
I could use a private setter on id, is that the answer? I find that when I set id myself elsewhere in the application I get inaccessible accessor. thanks.
Upvotes: 0
Views: 777
Reputation: 4119
IMHO you should create a new DTO for the model you want to bind, applying Single Responsibility Principle, and also is better for maintaining purposes. If you start inheriting from a base class, you will be facing later a huge problem if you need to change the contract of that class, like removing properties that you don't need and can affect the subclasses you have.
Now you can create
class ProjectWithOnlyName
{
public string name{get;set;}
}
and pass that instance as a parameter of your controller
public void MyControllerMethod([FromBody] ProjectWithOnlyName dto)
{
....
}
I would suggest a DTO for each action you are doing.
For update
class ProjectWithOnlyNameForUpdateDto
{
public string name{get;set;}
}
[HttpPut]
public void CreateMethod([FromBody] ProjectWithOnlyNameForUpdateDto dto)
{
....
}
For create
class ProjectWithOnlyNameForCreateDto
{
public string name{get;set;}
}
[HttpPost]
public void CreateMethod([FromBody] ProjectWithOnlyNameForCreateDto dto)
{
....
}
Hope this helps
Upvotes: 1