繁体   English   中英

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

[英]Error implementing a Custom Model Binder in Asp.Net Web API

我坚持这个非常奇怪的问题。
我有一个名为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方法可以看出,我有一个名为AttendenceRegistrationModelBinder的自定义ModelBinder ,这是代码

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

我在这做错了什么?

您遇到的问题是您使用的是MVC模型绑定器而不是WebApi。 看起来你是从System.Web.Mvc.DefaultModelBinder派生的,它实现了System.Web.Mvc.IModelBinder

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

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

这里这里有一些有用的资源。

您是否考虑为您的Json表单字段使用JToken ,这可能在没有自定义绑定器的情况下工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM