Web API optional parameters

前端 未结 3 555
野性不改
野性不改 2020-12-13 23:31

I have a controller with the following signature:

[Route(\"products/filter/{apc=apc}/{xpc=xpc}/{sku=sku}\")]
public IHttpActionResult Get(string apc, string          


        
相关标签:
3条回答
  • 2020-12-14 00:09

    Sku is an int, can't be defaulted to string "sku". Please check Optional URI Parameters and Default Values

    0 讨论(0)
  • 2020-12-14 00:18

    I figured it out. I was using a bad example I found in the past of how to map query string to the method parameters.

    In case anyone else needs it, in order to have optional parameters in a query string such as:

    • ~/api/products/filter?apc=AA&xpc=BB
    • ~/api/products/filter?sku=7199123

    you would use:

    [Route("products/filter/{apc?}/{xpc?}/{sku?}")]
    public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
    { ... }
    

    It seems odd to have to define default values for the method parameters when these types already have a default.

    0 讨论(0)
  • 2020-12-14 00:32

    you need only set default value to parameters(you do not need the Route attribute):

    public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
    { ... }
    
    0 讨论(0)
提交回复
热议问题