asp.net-mvcasp.net-mvc-4asp.net-web-apimodelbinder

WebAPI ModelBinder Error


I've implemented a ModelBinder but it's BindModel() method is not being called, and I get Error Code 500 with the following message:

Error:

Could not create a 'IModelBinder' from 'MyModelBinder'. Please ensure it derives from 'IModelBinder' and has a public parameterless constructor.

I do derive from IModelBinder and do have public parameterless constructor.

My ModelBinder Code:

public class MyModelBinder : IModelBinder
    {
        public MyModelBinder()
        {

        }
        public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            // Implementation
        }
    }

Added in Global.asax:

protected void Application_Start(object sender, EventArgs e)
{
    ModelBinders.Binders.DefaultBinder = new MyModelBinder();

    // ...
}

WebAPI Action Signature:

    [ActionName("register")]
    public HttpResponseMessage PostRegister([ModelBinder(BinderType = typeof(MyModelBinder))]User user)
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }

User Class:

public class User
{
    public List<Communication> Communications { get; set; }
}

Solution

  • ASP.NET Web API uses a completely different ModelBinding insfracture than APS.NET MVC.

    You are trying to implement the MVC's model binder interface System.Web.Mvc.IModelBinder but to work with Web API you need to implement System.Web.Http.ModelBinding.IModelBinder

    So your implementation should look like this:

    public class MyModelBinder : System.Web.Http.ModelBinding.IModelBinder
    {
        public MyModelBinder()
        {
    
        }
    
        public bool BindModel(
            System.Web.Http.Controllers.HttpActionContext actionContext, 
            System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
        {
            // Implementation
        }
    }
    

    For further reading: