asp.net-mvc – WebAPI ModelBinder错误

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

错误

不能
从’MyModelBinder’创建一个’IModelBinder’.请确保它来源
来自’IModelBinder’并且具有公共无参数
构造函数.

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

我的ModelBinder代码

public class MyModelBinder : IModelBinder
    {
        public MyModelBinder()
        {

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

在Global.asax中添加

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

    // ...
}

WebAPI行动签名:

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

用户类:

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

解决方法

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

您正在尝试实现MVC的模型绑定器接口System.Web.Mvc.IModelBinder,但要使用Web API,您需要实现System.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
    }
}

进一步阅读:

> Parameter Binding in ASP.NET Web API
> How WebAPI does Parameter Binding

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....