簡體   English   中英

WebAPI ModelBinder錯誤

[英]WebAPI ModelBinder Error

我已經實現了一個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
    }
}

進一步閱讀:

這適用於使用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();
    }
}

注意不同我希望它能幫到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM