문제

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; }
}
도움이 되었습니까?

해결책

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:

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top