Query string not working while using attribute routing

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

    With the Attribute routing you need to specify default values so they would be optional.

    [Route("{name}/{sport=Football}/{drink=Coke}")]
    

    Assigning a value will allow it to be optional so you do not have to include it and it will pass the value to specify.

    I have not tested the query string for this but it should work the same.

    I just re-read the question and I see that you have 2 Get verbs with the same path, I believe this would cause conflict as routing would not know which one to utilize, perhaps using the optional params will help. You can also specify one can be null and do checking in the method as to how to proceed.

    [Route("{name}/{sport?}/{drink?}")]
    

    Then check the variables in the method to see if they are null and handle as needed.

    Hope this helps, some? lol

    If not perhaps this site will, it has more details about attribute routing.

    http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

    Clip from that site:

    Optional parameters and default values You can specify that a parameter is optional by adding a question mark to the parameter, that is:

    [Route("countries/{name?}")]
    public Country GetCountry(string name = "USA") { }
    

    Currently, a default value must be specified on the optional parameter for action selection to succeed, but we can investigate lifting that restriction. (Please let us know if this is important.)

    Default values can be specified in a similar way:

    [Route("countries/{name=USA}")]
    public Country GetCountry(string name) { }
    

    The optional parameter '?' and the default values must appear after inline constraints in the parameter definition.

提交回复
热议问题