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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.