yo2011
yo2011

Reputation: 1021

Web api controller with multiple post methods with the same name but with different parameters

I have web api controller that has multiple post methods with the same name but with different parameters; when i run the application, i got an error:- Multiple actions were found that match the request note:- I don't want to use Action Routing as i want to unify my clients who use my web api

public Customer Post(Customer customer)
{

}

public Product Post(Product product)
{

}

Upvotes: 0

Views: 1381

Answers (2)

Eric Lease
Eric Lease

Reputation: 4194

You could use a single controller, with a single method taking a parameter of an interface type that both classes implement. Then call private handlers based on runtime type.

Upvotes: 0

Bill
Bill

Reputation: 413

The problem is that there's no way to distinguish between those two Post methods based on the URL that's getting passed to the web api.

The way to handle this would be to use a separate controller. One controller would be "api/Customer" and would have Post method that takes a Customer:

public class CustomerController : ApiController
{
    public Customer Post(Customer customer) { }
}

The other would be "api/Product" and take a Product:

public class ProductController : ApiController
{
    public Product Post(Product product) { }
}

If you really really wanted to pass both into one controller, you could create a class that has all the properties of both Customer and Product, and then look at the properties to figure out what just got passed into your controller. But... yuck.

public class EvilController : ApiController
{
    public ProductOrCustomer Post(ProductOrCustomer whoKnows)
    {
        // Do stuff to figure out if whoKnows has
        // Product properties or Customer properties
    }
}

Upvotes: 2

Related Questions