I'm trying to create a very simple model binder for ObjectId types in my models but can't seem to make it work so far.
Here's the model binder:
public class ObjectIdModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var result = bindingContext.ValueProvider.GetValue(bindingContext.FieldName);
return Task.FromResult(new ObjectId(result.FirstValue));
}
}
This is the ModelBinderProvider I've coded:
public class ObjectIdModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (context.Metadata.ModelType == typeof(ObjectId))
{
return new BinderTypeModelBinder(typeof(ObjectIdModelBinder));
}
return null;
}
}
Here's the class I'm trying to bind the body parameter to:
public class Player
{
[BsonId]
[ModelBinder(BinderType = typeof(ObjectIdModelBinder))]
public ObjectId Id { get; set; }
public Guid PlatformId { get; set; }
public string Name { get; set; }
public int Score { get; set; }
public int Level { get; set; }
}
This is the action method:
[HttpPost("join")]
public async Task<SomeThing> Join(Player player)
{
return await _someService.DoSomethingOnthePlayer(player);
}
For this code to work, I mean for the model binder to run, I inherited the controller from Controller and removed the [FromBody] attribute from the Player parameter.
When I run this, I can step into BindModelAsync method of the model binder, however I can't seem to get the Id parameter value from the post data. I can see the bindingContext.FieldName is correct; it is set to Id but result.FirstValue is null.
I've been away from Asp.Net MVC for a while, and it seems lots of things have been changed and became more confusing :-)
EDIT Based on comments I think I should provide more context.
If I put [FromBody] before the Player action parameter, player is set to null. If I remove [FromBody], player is set to a default value, not to the values I post. The post body is shown below, it's just a simple JSON:
{
"Id": "507f1f77bcf86cd799439011"
"PlatformId": "9c8aae0f-6aad-45df-a5cf-4ca8f729b70f"
}