I'm not sure this question matches this forum's purpose, but I didn't think it should belong to the stackoverflow one either, so here it goes:
I created a model binder that makes one mapping so "clean" by putting it in the model binder itself, but now I wanted to do it again in another action method and I was just wondering if there would be a better way to do it, since I'm not convinced that's the right place to do so.
My action method looks like this:
[HttpPost("Register")]
public async Task<IActionResult> Register(
[FromQuery] UserToRegister userToRegister,
User user /*This property is never used from the body request, since I set it in my custom Model Binder*/)
{
var response = await _userService.RegisterAsync(user);
return Ok(response);
}
I created a custom Model Binder, where I map the properties from userToRegister
into the user
param. So this custom binder looks like this:
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var values = bindingContext.ValueProvider;
User user = new User()
{
Id = Guid.NewGuid(),
Name = values.GetValue("Name").FirstValue,
Password = /*password encrypted*/,
...
};
bindingContext.Result = ModelBindingResult.Success(user);
return Task.CompletedTask;
}
So do you find it a good solution? Would it better to get the User
object in the request so I could modify it later? Should I do this modification (hashing the password, creating a new Id, etc) in the ModelBinder
?
UserToRegister
to theUser
object, so I'm getting some extra properties, such as the user's Id, or the hashed password... – Ferran R. May 29 '20 at 06:28