【问题标题】:Can you have 2 GET methods with different parameter types within the same web api controller? [duplicate]你可以在同一个 web api 控制器中有 2 个具有不同参数类型的 GET 方法吗? [复制]
【发布时间】:2016-03-20 06:23:04
【问题描述】:

我有一个带有 2 个 GET 方法的 asp.net web api 控制器。一个接受字符串参数,另一个接受 int 参数。我只有通过 web api 设置的默认路由。

        public HttpResponseMessage GetSearchResults(string searchTerm)
        {
            HttpResponseMessage response;
            //Do Work
            return response;
        }

        public HttpResponseMessage Get(int id)
        {
            HttpResponseMessage response;
            //Do Work
            return response;
        }

每次我在 URL 中传递一个 int 值时,都会调用接受字符串参数的 GET 方法。接受 int 参数的 GET 方法永远不会被调用。

是否可以在同一个控制器中拥有 2 个具有不同参数类型的 GET 方法?

-编辑- 建议的重复问题是不同的,因为它询问具有完全相同参数类型的 2 个方法 - 我询问的是不同的参数类型。

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-web-api asp.net-web-api2


    【解决方案1】:

    是的,这是可能的。使用默认配置开箱即用,假设您将 searchTerm 作为查询字符串参数传递,您所拥有的应该可以工作。但是,如果您尝试将其作为 URL 的一部分传递,例如 /api/myurl/blah,默认约定路由将尝试将其与方法的 int 版本匹配并返回错误。您必须编辑默认配置或使用Attribute Routing

    一般来说,我发现基于约定的 MVC 路由在 WebApi 中不太有用,所以我通常禁用它并使用 Attribute Routing

    要启用属性路由,请添加

    config.MapHttpAttributeRoutes();
    

    到您的 WebApi 配置。

    然后你可以这样标记你的方法

    [HttpGet]
    [Route("api/myobject/")]
    public HttpResponseMessage GetSearchResults(string searchTerm)
    {
        HttpResponseMessage response;
        //Do Work
        return response;
    }
    
    [HttpGet]
    [Route("api/myobject/{id:int}")]
    public HttpResponseMessage Get(int id)
    {
        HttpResponseMessage response;
        //Do Work
        return response;
    }
    

    现在,你可以调用第一个方法了

    /api/myobject?searchTerm=blah
    

    第二个途径

    /api/myobject/1
    

    它们不应该发生碰撞。

    但是,如果您想让searchTerm 出现在 URL 中而不是查询参数中,您可以将路由更改为

    [Route("api/myobject/{searchTerm}")]
    

    api/myobject/{id:int} 路由将捕获所有 id,api/myobject/{searchTerm} 将捕获大多数其他内容。但是,请注意这一点,就好像 URL 不是 URL 编码的,怪异的事情往往会发生。

    我不确切知道您正在寻找什么 URL 格式,所以我提供的只是简单的示例。我之前发布的link 更深入地研究了属性路由。它允许您创建比 WebApi 从 MVC 继承的约定路由更复杂的路由。

    【讨论】:

    • 很好的解释 - 属性路由完美运行!
    • 没问题。很高兴它有帮助。
    • 不错的有用答案,谢谢+1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 2017-04-30
    相关资源
    最近更新 更多