Web API optional parameters

前端 未结 3 554
野性不改
野性不改 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: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.

提交回复
热议问题