首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WebAPI ModelBinder误差

WebAPI ModelBinder误差
EN

Stack Overflow用户
提问于 2013-09-28 19:29:55
回答 2查看 5.9K关注 0票数 10

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

错误:

无法从“MyModelBinder”创建“IModelBinder”。请确保它是从'IModelBinder‘派生的,并且有一个公共的无参数构造函数。

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

我的ModelBinder代码:

代码语言:javascript
复制
public class MyModelBinder : IModelBinder
    {
        public MyModelBinder()
        {

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

在Global.asax:中添加

代码语言:javascript
复制
protected void Application_Start(object sender, EventArgs e)
{
    ModelBinders.Binders.DefaultBinder = new MyModelBinder();

    // ...
}

WebAPI动作签名:

代码语言:javascript
复制
    [ActionName("register")]
    public HttpResponseMessage PostRegister([ModelBinder(BinderType = typeof(MyModelBinder))]User user)
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }

用户类:

代码语言:javascript
复制
public class User
{
    public List<Communication> Communications { get; set; }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-09-28 19:45:27

ASP.NET Web使用的ModelBinding与APS.NET完全不同。

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

因此,您的实现应该如下所示:

代码语言:javascript
复制
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
票数 22
EN

Stack Overflow用户

发布于 2016-01-28 08:14:50

使用 System.Web.ModelBinding

代码语言:javascript
复制
 using System.Web.ModelBinding;
class clsUserRegModelBinder : IModelBinder
{
   public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
   {
        throw new NotImplementedException();
   }
}

System.Web.MVC报道

代码语言:javascript
复制
using System.Web.Mvc;


class clsUserRegModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,     ModelBindingContext bindingContext)
    {
        throw new NotImplementedException();
    }
}

注意到我希望它能帮助你

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19070869

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档