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

跟風遠走 提交于 2019-12-07 16:31:16

问题


im stuck with this very strange problem.
i have an API Controller named AttendanceController derived from APIControllerFA which is inturn derived from ApiController
here is the code

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 ");

            ...........

As can be seen on the PostAttendance method i have a custom ModelBinder named AttendenceRegistrationModelBinder for which this is the code

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);
        }


    }

but when i try to access this controller using the Fiddler. i get an error saying

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

what am i doing wrong here?


回答1:


The issue you are having is that you are using the MVC model binder not the WebApi. It looks like you are deriving from System.Web.Mvc.DefaultModelBinder which implements System.Web.Mvc.IModelBinder.

To create a custom model binder for WebApi you need to implement System.Web.Http.IModelBinder.

Take a look at the model binders available in WebApi e.g. the CompsiteModelBinder http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/f079d76e57b5#src%2fSystem.Web.Http%2fModelBinding%2fBinders%2fCompositeModelBinder.cs.

Some useful resources here and here.

Have you considered using a JToken for your Json form field this may work without a custom binder.



来源:https://stackoverflow.com/questions/13805915/error-implementing-a-custom-model-binder-in-asp-net-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!