Sam Shiles
Sam Shiles

Reputation: 11259

WebAPI, post one or collection objects to same action without changing message body

What I'm trying to do with allow someone to post either:

[{...}, {...}] or {...} to a route and for it to be correctly bound to:

... Post(IEnumerable<MyModel> models)

I've got it working fine if I post a collection ([{...}, {...}] but I would like it to create a collection with one object when I also post valid json as single object ({...})

The reason I'm trying to do this is because our API works dynamically against a model that is defined by the user at runtime and so I don't know if the uri represents a list or a single resource.

I could achieve this with a customer IModelBinder but I was wondering if there is a way of getting the jsonserializer to deal with this use case without any custom code?

Upvotes: 4

Views: 2632

Answers (1)

mayabelle
mayabelle

Reputation: 10014

One solution would be to have two API methods call a private method that performs the same logic. For example:

public HttpResponseMessage Post(IEnumerable<MyModel> models)
{
    return DoSomething(models);
}

public HttpResponseMessage Post(MyModel model)
{
    return DoSomething(new List<MyModel> { model });
}

private HttpResponseMessage DoSomething(IEnumerable<MyModel> models)
{
    // Do something
}

Web API would figure out which one gets called based on the parameters that get passed in, but both would share the same code under the covers.

Update: If your parameters are coming from the body, there are some solutions described here: How to work with ASP.Net WebApi overloaded methods?

Upvotes: 2

Related Questions