WebAPI ModelBinder错误

Avi*_*hen 9 asp.net-mvc modelbinder asp.net-mvc-4 asp.net-web-api

我已经实现了一个ModelBinder但它的BindModel()方法没有被调用,我得到错误代码500,并带有以下消息:

错误:

无法从"MyModelBinder"创建"IModelBinder".请确保它派生自'IModelBinder'并具有公共无参数构造函数.

我从IModelBinder派生,并有公共无参数构造函数.

我的ModelBinder代码:

public class MyModelBinder : IModelBinder
    {
        public MyModelBinder()
        {

        }
        public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            // Implementation
        }
    }
Run Code Online (Sandbox Code Playgroud)

在Global.asax中添加:

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

WebAPI行动签名:

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

用户类:

public class User
{
    public List<Communication> Communications { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

nem*_*esv 21

ASP.NET Web API使用与APS.NET MVC完全不同的ModelBinding insfracture.

您正在尝试实现MVC的模型绑定器接口,System.Web.Mvc.IModelBinder但要使用您需要实现的Web APISystem.Web.Http.ModelBinding.IModelBinder

所以你的实现应该是这样的:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

进一步阅读: