Optional Parameters in Web Api Attribute Routing

后端 未结 3 1530
小鲜肉
小鲜肉 2020-12-01 11:56

I want to handle POST of the following API-Call:

/v1/location/deviceid/appid

Additional Parameter are coming from the Post-Body.

This al

相关标签:
3条回答
  • 2020-12-01 12:07

    Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:

    [Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]
    

    The ? character is put always before the last } character

    For more information see: Optional URI Parameters and Default Values

    0 讨论(0)
  • 2020-12-01 12:18

    For an incoming request like /v1/location/1234, as you can imagine it would be difficult for Web API to automatically figure out if the value of the segment corresponding to '1234' is related to appid and not to deviceid.

    I think you should change your route template to be like [Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")] and then parse the deiveOrAppid to figure out the type of id.

    Also you need to make the segments in the route template itself optional otherwise the segments are considered as required. Note the ? character in this case. For example: [Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]

    0 讨论(0)
  • 2020-12-01 12:24

    Converting my comment into an answer to complement @Kiran Chala's answer as it seems helpful for the audiences-

    When we mark a parameter as optional in the action uri using ? character then we must provide default values to the parameters in the method signature as shown below:

    MyMethod(string name = "someDefaultValue", int? Id = null)

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