Query string not working while using attribute routing

后端 未结 8 2158
無奈伤痛
無奈伤痛 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:49

    Just a side note from my part as well. In order for queryString params to work, you need to provide a default value for your method parameters to make it optional. Just as you would also do when normally invoking a C# method.

    [RoutePrefix("api/v1/profile")]
    public class ProfileController : ApiController
    {
    
       ...
    
       [HttpGet]
       [Route("{profileUid}")]
       public IHttpActionResult GetProfile(string profileUid, long? someOtherId) 
       {
          // ...
       }
    
       ...
    
    }
    

    This allows me to call the endpoint like this:

    /api/v1/profile/someUid
    /api/v1/profile/someUid?someOtherId=123
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题