我已经实现了 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/