Search code examples
c#asp.net-web-apimodel-bindingcustom-model-binder

C# Web.API Cannot add custom model binder


I have API controller that has one Put method

public class ScheduleExecutionsController : ApiController
{

    public ScheduleExecutionsResponse Put([ModelBinder(typeof(TestBinder))]ScheduleExecutionsRequest requestInfo)
    {
        ....
    }
}

I added a binder class to the project

public class TestBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        return new ScheduleExecutionsRequest();
    }
}

I set 2 breakpoints. First one to the first line of Put method in controller and second to first line of my TestBinder BindModel object. After with Fiddler I send PUT request.

Debugger stops always inside my action but never inside BindModel methof of the binder. It seems that default binder is used. What did I miss to add custom one?


Solution

  • Are you using the WebAPI or MVC version of ModelBinderAttribute?

    Most of the infrastructure of MVC and WebAPI – filters, binding, etc. – exist in two forms (due to the history of the two libraries). Your WebAPI controllers and actions must use the WebAPI version of these (namespace System.Web.Http or its child namespaces)).