2013-03-07 74 views
1

使用web-api我转到/ api/cat/orders/在web-api中使用可选参数进行路由

我指定了以下路由和控制器方法。我预计会使用“ApiRouteWithCategoryAndExtId”路由和“GetMessageByCategoryExtId”方法,因为我使得“extid”是可选的。但它使用默认的Get方法。

(/ API/CAT /命令/ ID18采用GetMessageByCategoryExtId,但随后EXTID是不可选)

我在做什么错?

路线:

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

config.Routes.MapHttpRoute(
    name: "ApiRouteWithCategoryAndExtId", 
    routeTemplate: "api/cat/{category}/{extid}", 
    defaults: new { extid = RouteParameter.Optional, controller = "Default"} 
); 

控制器:

public string Get() 

public HttpResponseMessage GetMessageById(int id) 

public HttpResponseMessage GetMessageByCategoryExtId(
    string category, string extid) 
+1

什么是默认路由,是在这些其他路由之前还是之后定义的? – 2013-03-08 03:58:27

+0

这些是唯一的两条路线,所以我想第一条是默认的?它可能与te web-api惯例有关,或者它与基于模式的第一条路线匹配,而不是基于实际内容。但我不知道如何检查这里发生的事情。 – Sander 2013-03-08 19:03:00

回答

1

在这里,您将需要指定extid默认值:

public HttpResponseMessage GetMessageByCategoryExtId(
    string category, string extid **= null**) 

如果上述默认值不指定,webapi试图做一个严格t匹配动作的参数与可用值(通过路由参数或查询字符串值),因为这里您的url /api/cat/orders/没有“extid”的值,它不存在于路由值中,因此webapi无法匹配GetMessageByCategoryExtId