如何使用 short 类型的枚举使 Swagger 工作?



我目前正在开发 ASP.NET Web API 2(C#(,直到今天一直在使用Swashbuckle而没有问题。我向现有模型添加了一个属性并破坏了整个文档生成,因此每当我转到/help/ui/index#!/页面时,我现在都会看到以下内容:

500 : {"message":"An error has occurred."} 

下面的枚举是我添加到现有模型的新属性。如果我删除short类型继承,一切正常。关于如何使用 JsonConverter 或自定义过滤器来确保 Swagger 不会损坏的任何想法?

public enum TestEnum: short
{
Unknown = 0,
Green = 1
}

这是开机自检请求:

[Route("{id:int:min(1)}/customers"), HttpPost]
public IHttpActionResult PostCustomer(int id, [FromBody] CustomerModel customerModel)
{
return Ok();
}

当我向客户模型添加新属性时,当且仅当枚举的类型为 short 时,它才会失败。

感谢您的帮助!

不久前我启用了一个IDocumentFilter,它帮助我们显示枚举的整数和字符串值,以便为我们的客户提供更多有用的详细信息。

问题是这个类只将枚举强制转换为 INT,所以我不得不更新它以接受其他类型的。这是我正在使用的类:

public class SwaggerEnumDescriptions : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
// add enum descriptions to result models
foreach (KeyValuePair<string, Schema> schemaDictionaryItem in swaggerDoc.definitions)
{
Schema schema = schemaDictionaryItem.Value;
foreach (KeyValuePair<string, Schema> propertyDictionaryItem in schema.properties)
{
Schema property = propertyDictionaryItem.Value;
IList<object> propertyEnums = property.@enum;
if (propertyEnums?.Count > 0)
{
property.description += $": {DescribeEnum(propertyEnums)}";
}
}
}
// add enum descriptions to input parameters
if (swaggerDoc.paths.Count > 0)
{
foreach (PathItem pathItem in swaggerDoc.paths.Values)
{
DescribeEnumParameters(pathItem.parameters);
// head, patch, options, delete left out
List<Operation> 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 (Parameter param in parameters)
{
IList<object> paramEnums = param.@enum;
if (paramEnums?.Count > 0)
{
param.description += $": {DescribeEnum(paramEnums)}";
}
}
}
}
private string DescribeEnum(IList<object> enums)
{
List<string> enumDescriptions = new List<string>();
foreach (object enumOption in enums)
{
Type enumType = enumOption.GetType();
object enumValue =
Enum.GetUnderlyingType(enumType) == typeof(byte) ? (byte)enumOption :
Enum.GetUnderlyingType(enumType) == typeof(short) ? (short)enumOption :
Enum.GetUnderlyingType(enumType) == typeof(long) ? (long)enumOption :
(int)enumOption;
enumDescriptions.Add($"{enumValue} = {Enum.GetName(enumType, enumOption)}");
}
return string.Join(", ", enumDescriptions.ToArray());
}
}

为了在您的 API 上使用它,您需要将 IDocumentFilter 添加到 Swagger 配置:

c.DocumentFilter<SwaggerEnumDescriptions>();

最新更新