我正在使用Swagger-Net为我的API生成swagger文件。然后,我为前端自动生成代码。问题是我在枚举方面遇到了一些问题。我既需要枚举作为字符串,又需要枚举作为整数。因此,我想在属性的描述中添加枚举类型并生成以下代码:
{
"name": "genders",
"in": "query",
"description": "0 = Unknown\r\n1 = Male\r\n2 = Female",
"required": false,
"type": "array",
"items": {
"type": "number",
"format": "int32",
"enum": [
0,
1,
2
]
},
"collectionFormat": "multi"
},
{
"name": "ages",
"in": "query",
"description": "0 = Unknown\r\n1 = Age18to25\r\n2 = Age26to35\r\n3 = Age36to45\r\n4 = Age46to55\r\n5 = Age56to65\r\n6 = Age66toEnd\r\n8 = Age16to17",
"required": false,
"type": "array",
"items": {
"type": "number",
"format": "int32",
"enum": [
0,
1,
2,
3,
4,
5,
6,
8
]
},
"collectionFormat": "multi"
},
{
"name": "sortDirection",
"in": "query",
"description": "0 = None\r\n1 = Ascending\r\n2 = Descending",
"required": true,
"type": "number",
"format": "int32",
"enum": [
0,
1,
2
]
}
我可以通过使用Swashbuckle并实现IDocumentFilter来生成此代码。使用Swashbuckle的问题是System.Web.Http的版本不匹配,这就是为什么我需要使用Swagger-Net。我的IDocmentFilter看起来像这样:
public class SwaggerEnumDescriptionsFilter:IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
// add enum descriptions to result models
foreach (var schemaDictionaryItem in swaggerDoc.definitions)
{
var schema = schemaDictionaryItem.Value;
foreach (var propertyDictionaryItem in schema.properties)
{
var property = propertyDictionaryItem.Value;
var propertyEnums = property.@enum;
if (propertyEnums?.Count > 0)
{
property.description += DescribeEnum(propertyEnums);
}
}
}
// add enum descriptions to input parameters
if (swaggerDoc.paths.Count > 0)
{
foreach (var pathItem in swaggerDoc.paths.Values)
{
DescribeEnumParameters(pathItem.parameters);
// head, patch, options, delete left out
var possibleParameterisedOperations = new List<Operation> { pathItem.get, pathItem.post, pathItem.put };
possibleParameterisedOperations.FindAll(x => x != null).ForEach(x => DescribeEnumParameters(x.parameters));
}
}
}
private void DescribeEnumParameters(IList<Parameter> parameters)
{
if (parameters != null)
{
foreach (var param in parameters)
{
var paramEnums = param.@enum;
if (paramEnums?.Count > 0)
{
param.description += DescribeEnum(paramEnums);
}
}
}
}
private string DescribeEnum(IList<object> enums)
{
var enumDescriptions = new List<string>();
foreach (var enumOption in enums)
{
var enumType = enumOption.GetType();
object enumValue =
Enum.GetUnderlyingType(enumType) == typeof(byte) ? (byte)enumOption :
Enum.GetUnderlyingType(enumType) == typeof(long) ? (long)enumOption :
(int)enumOption;
enumDescriptions.Add(string.Format("{0} = {1}", enumValue, Enum.GetName(enumType, enumOption)));
}
return string.Join("\r\n", enumDescriptions);
}
}
我发现 property。@ enum 不是Swagger-Net中的枚举。它已经是一个int了。有谁知道我该如何配置Swagger-Net来保留枚举类型?