Asp.net-Mvc
WebAPI ModelBinder 錯誤
我已經實現了一個
ModelBinder但它的BindModel()方法沒有被呼叫,我得到錯誤程式碼 500 並顯示以下消息:錯誤:
無法從“MyModelBinder”創建“IModelBinder”。請確保它派生自“IModelBinder”並具有公共無參數建構子。
我確實從 IModelBinder 派生並且確實有公共無參數建構子。
我的模型綁定器程式碼:
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 的模型綁定器介面
System.Web.Mvc.IModelBinder,但要使用您需要實現的 Web APISystem.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 } }進一步閱讀: