Web API控制器中的多个GET方法
问题描述:
使用Web API时,遇到从客户端调用GET方法时的情况。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
}
答
我需要看到调用代码和路由配置是肯定的,但我的猜测是,您可能正在使用宁静的路由。切换到使用查询字符串,命名参数和所有的方法应该工作:
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值,因为它会创建一个模糊的条件。
您可能想在以下链接查看参数绑定的详细信息。在Web Api 2中绑定可能有点棘手,因为默认包含的模型绑定器和格式化器在幕后执行了大量工作。
http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
ThanxBlll,它真的听起来是对问题的解释。该链接真的很有帮助。 –