【问题标题】:Multiple GET methods in a Web API ControllerWeb API 控制器中的多个 GET 方法
【发布时间】:2015-09-07 09:52:01
【问题描述】:

在使用 Web API 时,遇到了从客户端调用 GET 方法的情况。

//This didn't worked
public IEnumerable<type> Get(string mode)
{
    //Code
}

//This worked
public IEnumerable<type> Get(string id)
{
    //Code
}

只需更改参数名称即可使我的调用成功。我正在使用默认路由。

这种方法有什么问题。如果我想要一个带有多个参数的 GET 方法怎么办。例如:

pulbic string GET(string department, string location)
{
    //Code here
}

【问题讨论】:

    标签: asp.net-web-api2 asp.net-web-api-routing


    【解决方案1】:

    我需要查看调用代码和路由配置才能确定,但​​我的猜测是您可能正在使用静态路由。切换到使用带有命名参数的查询字符串,您的所有方法都应该可以工作:

    http://api/yourcontroller?id=something

    http://api/yourcontroller?mode=somethingelse

    http://api/yourcontroller?department=adepartment&location=alocation

    默认路由模板配置理解 id。您可能会在 WebApiConfig 静态类方法 Register 的 App_Start 文件夹中看到这一点。

    这是默认设置:

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    

    基于此默认设置,操作方法参数 (id) 被设置为路由数据的一部分,这就是您上面列出的控制器代码中的第二个操作方法可以工作的原因。您将无法使用模板路由或属性路由在 get 中为同一控制器中的多个单参数 get 方法设置值,因为这会产生模棱两可的条件。

    您可能希望在以下链接中查看有关参数绑定的详细信息。在 Web Api 2 中绑定有时会有点棘手,因为默认包含的模型绑定器和格式化程序在幕后做了很多工作。

    http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

    【讨论】:

    • Thanx BIll,这听起来确实是对问题的解释。这个链接真的很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多