我已经实现了一个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; }
}发布于 2013-09-28 19:45:27
ASP.NET Web使用的ModelBinding与APS.NET完全不同。
您正在尝试实现MVC的模型绑定接口System.Web.Mvc.IModelBinder,但是要使用Web,您需要实现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
}
}请进一步阅读:
发布于 2016-01-28 08:14:50
使用 System.Web.ModelBinding
using System.Web.ModelBinding;
class clsUserRegModelBinder : IModelBinder
{
public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
{
throw new NotImplementedException();
}
}为 System.Web.MVC报道
using System.Web.Mvc;
class clsUserRegModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
throw new NotImplementedException();
}
}注意到我希望它能帮助你
https://stackoverflow.com/questions/19070869
复制相似问题