Search code examples
c#asp.net-coreswaggerasp.net-core-2.1swashbuckle

ASP.NET Core 2.1 Swagger(swashbuckle) Url template optional parameter


[HttpGet("commercial/{fromCcy}/{toCcy?}")]
public ActionResult Commercial(string fromCcy, string toCcy)

I have action "commercial" with optional parameter "toCcy" and swagger spec generates with required field. Is there any way to solve this problem?

enter image description here


Solution

  • When you use optional parameters, the best way is use [Fromquery]. For example:

    [HttpGet("commercial")]
    public ActionResult Commercial([FromQuery] OptionsViewModel viewModel)
    {
    ...
    }
    
    public class OptionsViewModel
    {
        public string FromCcy { get; set; }
        public string ToCcy { get; set; }
    }
    

    Then Swagger shows all parameters as optional:

    Swagger UI Parameters:
    
    Name    Description
    FromCcy
    string
    (query)  
    
    ToCcy
    string
    (query)