更新:我开始怀疑这是否是因为一个bug:
https://github.com/domaindrivendev/Swashbuckle/issues/590
但解决办法似乎并没有解决我的问题。
我使用Swashbuckle为C# ASP.NET Web项目生成API文档。
我的目标是允许以下内容作为有效的URL:
/endpoint/items/123/foo?param2=bar
将必需参数(param1)设置为"foo“,将可选参数(param2)设置为"bar”。我希望两个参数都包含在单个C#参数对象中。(使用其他可选参数,如param3等)。几个端点将使用相同的参数,我希望有一个表示参数的对象。
Swagger/Swashbuckle的细节主要是一个黑匣子,我无法弄清楚这一点。我在参数列表中得到了副本。
再现问题的示例代码:
// This endpoint is generating documentation the way I would like.
[HttpGet]
[Route("endpoint1/items/{id}/{param1}")]
public string GetDataForParameters(int id, string param1, string param2 = null, string param3 = null)
{
return string.Format("Params: {1}, {2}, {3}", id, param1, param2, param3);
}
// This endpoint has the structure I would like, but I get duplicates for param1 in the documentation.
[HttpGet]
[Route("endpoint2/items/{id}/{param1}")]
public string GetDataForParameters(int id, [FromUri(Name = "")]MyParams myParams)
{
return string.Format("Params: {1}, {2}, {3}", id, myParams.Param1, myParams.Param2, myParams.Param3);
}
public class MyParams
{
public string Param1 { get; set;}
public string Param2 { get; set;}
public string Param3 { get; set;}
}
使用第二个方法,我接收单个对象内的参数。但是Swagger会为"param1“显示一个重复条目。
截图:摆幅重复参数
如何使Swagger/Swashbuckle不显示"param1“的第二个条目?
之所以有这种结构,是因为我有多个端点,它们返回不同类型的数据,但它们使用公共参数。有些参数是必需的(以及ID的prt ),因此我们希望将这些参数包含在URL中,并在查询字符串中包含可选参数。我希望公共参数对象应该包括必需参数和可选参数。
用VisualStudio2015UPDATE 1创建的示例代码。默认ASP.NET Web项目。将上面的代码添加到生成的ValuesController.cs中。安装的软件包Swashackle5.3.1+依赖项。
发布于 2016-02-18 03:17:40
更新:找到了解决办法。太丑了:
Swagger随后将获取该方法参数和文档。ASP.Net将为方法参数和参数对象指定参数,从而允许代码使用参数对象。
/// <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;}
}
我不会使用这种方法,对于任何其他阅读代码的开发人员来说,这都太令人困惑了。因此不幸的是,Swagger/Swashbuckle实际上迫使我更改我的(完全工作的)代码,以生成文档。
除非有人能提出适当的解决方案,我认为最好的解决办法是有简单的方法参数。
发布于 2016-02-23 05:28:06
当Swashbuckle生成它的swagger.json文件时,它会查看路由和查询参数,所以当您使用Get(string param1, string param2 ..)
时,它会自动告诉Swashbuckle这些参数是必需的(因为它们没有被设置为= null
)。
当使用annotations(System.ComponentModel.DataAnnotations)在您的模型中查找数据时,告诉是否需要参数。
将Param1设置为必需
public class MyParams
{
[Required]
public string Param1 { get; set;}
public string Param2 { get; set;}
public string Param3 { get; set;}
}
https://stackoverflow.com/questions/35478197
复制相似问题