【问题标题】:ASP.NET Web API routing and action selectionASP.NET Web API 路由和操作选择
【发布时间】:2013-06-15 15:57:10
【问题描述】:

我的控制器的路由和操作选择有问题。 我的路由看起来像:

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

我的控制器看起来像:

[HttpGet]
public Customers GetCustomers()
{
}

[HttpGet]
public Customer GetCustomerDetail(int id)
{
}

[ActionName("orders")]
[HttpGet]
public Orders GetCustomerOrders(int id)
{
}

我可以打电话给http://localhost/customers,也可以打电话给http://localhost/customers/1/orders。 但是当我尝试调用 http://localhost/customers/1 时,我会收到错误消息“找到与请求匹配的多个操作:”(与 GetCustomerDetail 和 GetCustomerOrders 匹配)。

知道如何解决这个问题吗?

谢谢

【问题讨论】:

  • 明确调用您的操作,http://localhost/customers/GetCustomerDetail/1
  • 是的,好的,但这不是我想要达到的目标 ;-) 而且这根本不合逻辑。它应该是'localhost/customers/1'。

标签: c# asp.net asp.net-web-api asp.net-web-api-routing


【解决方案1】:

您可以将路由更改为:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "{controller}",
    defaults: new { action = "GetCustomers" });

config.Routes.MapHttpRoute(
    name: "DefaultApiWithIdAndAction",
    routeTemplate: "{controller}/{id}/{action}",
    defaults: new { action="GetCustomerDetail" });

编辑: 如果您的所有控制器方法都遵循相同的模式,您可以执行以下操作:

[ActionName("default")]
[HttpGet]
public Customers GetCustomers()
{
}

[ActionName("default")]
[HttpGet]
public Customer GetCustomerDetail(int id)
{
}

[ActionName("orders")]
[HttpGet]
public Orders GetCustomerOrders(int id)
{
}

然后您可以使用一条路线:

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

【讨论】:

  • 如果你在这个结构中有多个控制器,这听起来像是很多工作。真是一团糟!!!
  • 我为答案添加了一个更通用的解决方案。
猜你喜欢
  • 2018-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多