【问题标题】:Web api controller with multiple post methods with the same name but with different parameters具有多个同名但参数不同的 post 方法的 Web api 控制器
【发布时间】:2015-04-17 06:14:50
【问题描述】:

我有一个 web api 控制器,它有多个同名但参数不同的 post 方法;当我运行应用程序时,出现错误:- 找到多个与请求匹配的操作 注意:- 我不想使用动作路由,因为我想统一使用我的 web api 的客户

public Customer Post(Customer customer)
{

}

public Product Post(Product product)
{

}

【问题讨论】:

    标签: http-post asp.net-web-api


    【解决方案1】:

    问题在于,无法根据传递给 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
        }
    }
    

    【讨论】:

    • 不,这些解决方案不适用,因为它会增加我的 api 的复杂性
    • @Bill 的解决方案应该是您想要构建安静的 Web 服务的正确答案。每个控制器将负责一个资源(产品或客户)。不可能两者兼而有之。如果要将两者都保留在同一个控制器中,则需要指定一个 RouteAttribute 并获得与使用两个控制器相同的结果,但组织性较差。
    【解决方案2】:

    您可以使用一个控制器,一个方法采用两个类都实现的接口类型的参数。然后根据运行时类型调用私有处理程序。

    【讨论】:

    • 我想知道返回类型将如何。至少只要 op 必须返回一个 .net 对象并且还不够,即 jsonresult。
    • 如何实现这个解决方案?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2017-04-15
    • 2019-03-24
    • 2017-03-10
    • 2020-09-19
    • 2016-03-20
    相关资源
    最近更新 更多