Web.API MapHttpRoute parameters

前端 未结 3 1351
小蘑菇
小蘑菇 2021-02-04 02:48

I\'m having problems with my Web.API routing. I have the following two routes:

config.Routes.MapHttpRoute(
    name: \"Me         


        
3条回答
  •  天命终不由人
    2021-02-04 03:02

    The reason you are seeing this problem is because your first route will match both requests. The id and type token in the URL will match both requests because when the route is being run, it will try parse the URL and match each segment against your URL.

    So your first route will happily match both requests as follows.

    ~/methodone/1/mytype => action = methodone, id = 1, and type = mytype
    ~/methodtwo/directory/report => action = methodtwo, id = directory, and type = report
    

    To work around this, you should use route like

    config.Routes.MapHttpRoute(
        name: "MethodOne",
        routeTemplate: "api/{controller}/methodone/{id}/{type}",
        defaults: new { id = RouteParameter.Optional, type = RouteParameter.Optional }
    );
    
    config.Routes.MapHttpRoute(
        name: "MethodTwo",
        routeTemplate: "api/{controller}/methodtwo/{directory}/{report}",
        defaults: new { directory = RouteParameter.Optional, report = RouteParameter.Optional }
    );
    

    Even if you use WebGet, you might need to do something similarly to disambiguous those two methods I believe.

提交回复
热议问题