Duplicate parameter output in Swagger

萝らか妹 提交于 2019-12-05 08:17:36

Update: Found a workaround. It's ugly:

  1. Introduce an explicit duplicate parameter in the method.
  2. Add JsonIgnore attribute to the duplicate properties in the parameter object.

Swagger will then pick up the method parameter and documentation for this one. ASP.Net will assign parameters to BOTH the method parameter and the parameter object, allowing the code to use the parameter object.

    /// <param name="param1">URL parameters must be documented on this level.</param>
    [HttpGet]
    [Route("endpoint2/items/{id}/{param1}")]
    public string GetDataForParameters(int id, string param1, [FromUri(Name = "")]MyParams myParams)
    {
        // the param1 method parameter is a dummy, and not used anywhere.
        return string.Format("Params: {1}, {2}, {3}", id, myParams.Param1, myParams.Param2, myParams.Param3);
    }

    public class MyParams
    {
        /// <summary>
        /// Cannot add documentation here, it will be ignored.
        /// </summary>
        [JsonIgnore]
        public string Param1 { get; set;}
        /// <summary>
        /// This is included. Querystring parameters can be documented in this class.
        /// </summary>
        public string Param2 { get; set;}
        public string Param3 { get; set;}
    }

I will not use this approach, it will be too confusing for any other developer reading the code. So unfortunately, Swagger/Swashbuckle has in pratice forced me to change my (fully working) code in order to generate documentation.

Unless anyone can suggest a proper solution I think the best solution is to have plain method parameters.

When Swashbuckle generates its swagger.json file it looks at routing and query parameters So when you use Get(string param1, string param2 ..) that automatically tells Swashbuckle that those parameters are required (because they are NOT set to = null)

When using Get([FromUri(Name = "")]MyParams myParams) Swashbuckle looks for data annotations(System.ComponentModel.DataAnnotations) in your model, to tell wether or not a parameter is required or not.

Set Param1 to be required

public class MyParams
    {
        [Required]
        public string Param1 { get; set;}
        public string Param2 { get; set;}
        public string Param3 { get; set;}
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!