WHAT I HAVE
I have an api controller (ASP.NET Core MVC) with the following method:
[HttpPost]
[Route("delete")]
public Task<ActionResult> SomeAction(Guid[] ids, UserToken userToken, CancellationToken cancellationToken)
{
....
}
I have a custom model binder and binder provider:
public class UserTokenBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Metadata.ModelType == typeof(UserToken))
{
return new BinderTypeModelBinder(typeof(UserTokenBinder));
}
return null;
}
}
public class UserTokenBinder: IModelBinder
{
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
var token = await bindingContext.ActionContext.HttpContext.User.ToUserTokenAsync(CancellationToken.None);
bindingContext.Result = ModelBindingResult.Success(token ?? UserToken.UnidentifiedUser);
}
}
Added the binder provider to services:
services.AddMvc(options =>
{
options.ModelBinderProviders.Insert(0, new UserTokenBinderProvider());
});
THE ISSUE
While server is loading I'm getting the following exception (InvalidOperationException
):
... 'SomeAction' has more than one parameter that was specified or inferred as bound from request body. Only one parameter per action may be bound from body. Inspect the following parameters, and use 'FromQueryAttribute' to specify bound from query, 'FromRouteAttribute' to specify bound from route, and 'FromBodyAttribute' for parameters to be bound from body: Guid[] ids, UserToken userToken
It seems that MVC disregards the custom binder I have for the UserToken
type and tries to bind it using default methods.
Any ideas why?
EDIT After receiving an answer here, an issue was opened to amend ASP.NET Core documentation.