Query string not working while using attribute routing

后端 未结 8 2264
無奈伤痛
無奈伤痛 2020-11-27 12:52

I\'m using System.Web.Http.RouteAttribute and System.Web.Http.RoutePrefixAttribute to enable cleaner URLs for my Web API 2 application. For most of

8条回答
  •  感情败类
    2020-11-27 13:50

    Since you have [Route("{name}/{drink}/{sport?}")] as attribute routing, this code will never be hit.

    config.Routes.MapHttpRoute(
    name: "NameRoute",
    routeTemplate: "{verId}/Names/{name}/{sport}/{drink}",
    defaults: new { name = RouteParameter.Optional, sport = RouteParameter.Optional, drink = RouteParameter.Optional },
    constraints: new { verId = @"\d+" });
    

    So only the attribute route [Route("{name}/{drink}/{sport?}")] is going to be honored here. Since your request localhost:12345/1/Names?name=Ted&sport=rugby&drink=coke, doesn't have name, sport or drink in the URL it is not going to match this attribute route. We do not consider the query string parameters when matching the routes.

    To solve this, you need to make all 3 optional in your attribute route. Then it will match the request.

提交回复
热议问题