asp.net-mvc - WebAPI ModelBinder 错误

标签 asp.net-mvc asp.net-mvc-4 asp.net-web-api modelbinder

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

错误:

不能 从“MyModelBinder”创建一个“IModelBinder”。请确保它派生 来自“IModelBinder”并且具有公共(public)无参数 构造函数。

我确实从 IModelBinder 派生,并且有公共(public)无参数构造函数。

我的 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 基础结构。

您正在尝试实现 MVC 的模型绑定(bind)器接口(interface) 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
    }
}

进一步阅读:

关于asp.net-mvc - WebAPI ModelBinder 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19070869/

相关文章:

jquery 代码适用于除 ie8 之外的所有浏览器

c# - 如何警告用户他们的网络 session 即将超时?

ASP.net MVC 复选框问题

jquery - 选择取消选择带有复选框的 kendo UI 网格行

c# - Web Api 2 中的 Mvc 样式参数绑定(bind)?

Azure AAD - 受众无效

css - 调试无更新时更新 .css 文件。 ASP.NET MVC 2

asp.net-mvc - 剑道不会加载一些文化信息

c# - MVC 操作未在 Controller 中触发

asp.net-web-api - ASP.NET Web API中的回调方法