Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }
}
like image 731
Aviran Cohen Avatar asked Sep 28 '13 19:09

Aviran Cohen


2 Answers

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:

  • Parameter Binding in ASP.NET Web API
  • How WebAPI does Parameter Binding
like image 167
nemesv Avatar answered Sep 24 '22 20:09

nemesv


This for using System.Web.ModelBinding

 using System.Web.ModelBinding;
class clsUserRegModelBinder : IModelBinder
{
   public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
   {
        throw new NotImplementedException();
   }
}

This for System.Web.MVC

using System.Web.Mvc;


class clsUserRegModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,     ModelBindingContext bindingContext)
    {
        throw new NotImplementedException();
    }
}

Note the Different i hope it help you

like image 36
Khalid Avatar answered Sep 20 '22 20:09

Khalid