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

1

3

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?

Catalog answered 10/12, 2012 at 17:23 Comment(0)
U
11

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.

Unknow answered 11/12, 2012 at 10:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.