简体   繁体   中英

Routing with optional parameter in web-api

Using web-api i go to /api/cat/orders/

I specified the following routes and controller methods. I expected that the "ApiRouteWithCategoryAndExtId" route and the "GetMessageByCategoryExtId" method would be used since I made "extid" optional. But it is using the default Get method.

(/api/cat/orders/id18 uses GetMessageByCategoryExtId, but then extid is not optional)

What am I doing wrong?

Routes:

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"}
);

Controller:

public string Get()

public HttpResponseMessage GetMessageById(int id)

public HttpResponseMessage GetMessageByCategoryExtId(
    string category, string extid)

Here you would need to specify a default value for extid :

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

if the above default value is not specified, webapi tries to do a strict matching of an action's parameters with available values(via route parameters or query string values) and since here your url here /api/cat/orders/ does not have a value for 'extid', it isn't present in the route values and hence webapi cannot match to GetMessageByCategoryExtId .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM