在Asp.Net Web API中实现自定义模型绑定器时出错

时间:2012-12-10 17:23:47

标签: c# asp.net-mvc-4 asp.net-web-api custom-model-binder

我坚持这个非常奇怪的问题 我有一个名为AttendanceController的API控制器派生自APIControllerFA,它来自ApiController。 这是代码

public class AttendanceController : ApiControllerFA
    {
        public HttpResponseMessage PostAttendance([ModelBinder(typeof(AttendanceRegistrationModelBinder))]AttendanceRegistrationModel model)
        {
            //checking model state for errors
            //throw new Exception("Just to throw an error ");

            ...........

从PostAttendance方法可以看出,我有一个名为ModelBinder的自定义AttendenceRegistrationModelBinder,这是代码

public class AttendanceRegistrationModelBinder :  DefaultModelBinder
    {

        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
        {
            if (propertyDescriptor.Name == "formJson")
            {
                string val = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name).AttemptedValue;
                dynamic jsonVal = JsonConvert.DeserializeObject(val);
                propertyDescriptor.SetValue(bindingContext.Model, jsonVal);
                return;
                //SetProperty(controllerContext, bindingContext,propertyDescriptor,jsonVal);
            }
            base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
        }


    }

但是当我尝试使用Fiddler访问此控制器时。我收到错误说

Could not create a 'IModelBinder' from 'AttendanceRegistrationModelBinder'. Please ensure it derives from 'IModelBinder' and has a public parameterless constructor

我在这里做错了什么?

1 个答案:

答案 0 :(得分:11)

您遇到的问题是您使用的是MVC模型绑定器而不是WebApi。看起来您是从实现System.Web.Mvc.DefaultModelBinder的{​​{1}}派生的。

要为WebApi创建自定义模型绑定器,您需要实现System.Web.Mvc.IModelBinder

查看WebApi中可用的模型绑定器,例如CompsiteModelBinder http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/f079d76e57b5#src%2fSystem.Web.Http%2fModelBinding%2fBinders%2fCompositeModelBinder.cs

一些有用的资源herehere

您是否考虑过在您的Json表单字段中使用JToken,这可能会在没有自定义绑定器的情况下运行。