使用web-api中的可选参数进行路由

时间:2013-03-07 18:16:10

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

使用web-api我去/ api / cat / orders /

我指定了以下路由和控制器方法。我期望使用“ApiRouteWithCategoryAndExtId”路由和“GetMessageByCategoryExtId”方法,因为我将“extid”作为可选项。但它使用的是默认的Get方法。

(/ api / cat / orders / 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 个答案:

答案 0 :(得分:1)

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

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

如果未指定上述默认值,webapi会尝试严格匹配操作的参数与可用值(通过路由参数或查询字符串值),因为此处您的网址/api/cat/orders/没有'extid'的值,它不在路线值中,因此webapi无法与GetMessageByCategoryExtId匹配。

相关问题