【发布时间】:2015-04-17 06:14:50
【问题描述】:
我有一个 web api 控制器,它有多个同名但参数不同的 post 方法;当我运行应用程序时,出现错误:- 找到多个与请求匹配的操作 注意:- 我不想使用动作路由,因为我想统一使用我的 web api 的客户
public Customer Post(Customer customer)
{
}
public Product Post(Product product)
{
}
【问题讨论】:
我有一个 web api 控制器,它有多个同名但参数不同的 post 方法;当我运行应用程序时,出现错误:- 找到多个与请求匹配的操作 注意:- 我不想使用动作路由,因为我想统一使用我的 web api 的客户
public Customer Post(Customer customer)
{
}
public Product Post(Product product)
{
}
【问题讨论】:
问题在于,无法根据传递给 Web api 的 URL 来区分这两个 Post 方法。
处理此问题的方法是使用单独的控制器。一个控制器将是“api/Customer”,并具有采用 Customer 的 Post 方法:
public class CustomerController : ApiController
{
public Customer Post(Customer customer) { }
}
另一个是“api/Product”并取一个产品:
public class ProductController : ApiController
{
public Product Post(Product product) { }
}
如果您真的想将两者都传递到一个控制器中,您可以创建一个包含 Customer 和 Product 的所有属性的类,然后查看属性以确定刚刚传递到控制器的内容。但是......糟糕。
public class EvilController : ApiController
{
public ProductOrCustomer Post(ProductOrCustomer whoKnows)
{
// Do stuff to figure out if whoKnows has
// Product properties or Customer properties
}
}
【讨论】:
您可以使用一个控制器,一个方法采用两个类都实现的接口类型的参数。然后根据运行时类型调用私有处理程序。
【讨论】: