Question

I'm using MongoDB with an ASP.NET Web Api (2) application, and want to accept ObjectId arguments in the Web Api methods.

I've written a custom model binder for the ObjectId type, and it when adding it to the Get method of a controller, everything works.

[Route("{id}")] public HttpResponseMessage Get(String type, [ModelBinder(typeof(ObjectIdModelBinder))]ObjectId id) {

But I need to do this in several methods and controllers, so I would rather put it somewhere central. I've read that I can register the binder centrally like this:

public static void Register(HttpConfiguration config) {
    var provider = new SimpleModelBinderProvider(typeof(ObjectId), new ObjectIdModelBinder());
    config.Services.Insert(typeof(ModelBinderProvider), 0, provider);
}

But that's not working!

Any ideas? Not really sure what the config.Services collection should contain, but I'm having a hard time locating the binder I insert.

Was it helpful?

Solution

With WebAPI even if you register a model binder, you still need to attach the [ModelBinder] to the input parameter, you just don't have to specify the type anymore so your method now looks like this:

[Route("{id}")]
public HttpResponseMessage Get(String type, [ModelBinder]ObjectId id) {

If you want to skip adding the attribute every time you declare a parameter of this type, then you have to look at writing a custom IActionValueBinder (which can be made very simple if you just extend the DefaultActionValueBinder) which is the default implementation. You might want to look at this post for pointers:

http://www.strathweb.com/2013/04/asp-net-web-api-parameter-binding-part-1-understanding-binding-from-uri/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top