Skip to content

Combining with Custom Model Binder #43

Description

@Luke1979

Hi all,

Great nuget package; thanks.

Is it possible to combining HybridModelBinder with another Custom IModelBinder.

My Request class has a complex type (Company) which I'm attempting to resolve using CompanyModelBinder in the example below. If I use [FromQuery] it all works, but changing to [FromHybrid] prevents the model binder from being hit.

Any help/info would be great.

CompanyModelBinder.cs

    public class CompanyModelBinderProvider: IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            return context.Metadata.ModelType == typeof(Company) 
                ? new CompanyModelBinder() 
                : null;
        }
    }

    public class CompanyModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
                throw new ArgumentNullException(nameof(bindingContext));

            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (valueProviderResult == ValueProviderResult.None)
                return Task.CompletedTask;

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

            var value = valueProviderResult.FirstValue;

            if (string.IsNullOrEmpty(value)) 
                return Task.CompletedTask;
            
            var model = new Company(value);

            bindingContext.Result = ModelBindingResult.Success(model);

            return Task.CompletedTask;
        }
    }

Startup.cs....

services
                .AddMvc(config =>
                {
                    // Custom Model Binders.
                    config.ModelBinderProviders.Insert(0, new CompanyModelBinderProvider());
                 })
                .AddHybridModelBinder();

Request.cs

public class Request : IRequest<Result<Response>>
{
    public Company Company { get; set; }
}

Controller.cs

Using [FromQuery] works (The Company model binder is invoked)

public IActionResult Index([FromQuery]Request request)
{
   ...
}

...but using [FromHybrid]` doesn't.... :(

public IActionResult Index([FromHybrid]Request request)
{
   ...
}
GET /api/v1/company?company=Foo HTTP/1.1
Host: localhost:44398

Any ideas what I might be doing wrong?

Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions