2

The default binder in web api expecst

http://url.com/webapi/Report/?PageIds=3243&PageIds=2365

To bind to

public IHttpActionResult Report(List<int> PageIds){ // exciting webapi code}

I wish to bind http://url.com/webapi/Report/?PageIds=3243,2365

as I am running out of space in my URL to do a GET.

I have created a class public class CommaSeparatedModelBinder :

System.Web.Http.ModelBinding.IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
           //Binding in here
        }
     }

and registered this in my WebApiConfig.cs

 var provider = new SimpleModelBinderProvider(
           typeof(List<int>), new CommaSeparatedModelBinder());
            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);

I have altered my method signature to use the model binder like so

 public IHttpActionResult Report( [ModelBinder] List<int> PageIds){ // exciting webapi code}

However a break point in my binder is not being hit (and the list does not get bound).

What else do I need to configure?

0

1 Answer 1

2

Make sure to follow all of the steps in this article: Parameter Binding in ASP.NET Web API

It appears you are missing the last step:

With a model-binding provider, you still need to add the [ModelBinder] attribute to the parameter, to tell Web API that it should use a model binder and not a media-type formatter. But now you don’t need to specify the type of model binder in the attribute:

   public HttpResponseMessage Get([ModelBinder] GeoPoint location) { ... }

Also, I've never tried binding to List<int>. You may not be able to model bind to it because it is a build-in type. If so, just box it with a custom class type and make sure to add the [ModelBinder] attribute to the class.

OR....

A better solution: KISS

public IHttpActionResult Report(string PageIds)
{
     var ids = PageIds.Split(',');
     // exciting web api code and/or more robust checking of the split
}
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately I did not miss that step... just missed putting it in my question :) see the edit! I will try the box and the fallback which I admit had not occurred to me! I prefer to keep things strongly typed if possible!

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.