是否有一种方法显示所有枚举作为他们的字符串值在swagger而不是他们的int值?

我希望能够提交POST动作,并根据它们的字符串值放置枚举,而不必每次都查看enum。

我尝试了DescribeAllEnumsAsStrings,但服务器然后接收字符串而不是enum值,这不是我们要寻找的。

有人解决了吗?

编辑:

public class Letter 
{
    [Required]
    public string Content {get; set;}

    [Required]
    [EnumDataType(typeof(Priority))]
    public Priority Priority {get; set;}
}


public class LettersController : ApiController
{
    [HttpPost]
    public IHttpActionResult SendLetter(Letter letter)
    {
        // Validation not passing when using DescribeEnumsAsStrings
        if (!ModelState.IsValid)
            return BadRequest("Not valid")

        ..
    }

    // In the documentation for this request I want to see the string values of the enum before submitting: Low, Medium, High. Instead of 0, 1, 2
    [HttpGet]
    public IHttpActionResult GetByPriority (Priority priority)
    {

    }
}


public enum Priority
{
    Low, 
    Medium,
    High
}

当前回答

对于我们正在寻找的东西,我在其他答案中发现了一些缺点,所以我想我将提供我自己的看法。我们使用ASP。NET Core 3.1与System.Text。Json,但我们的方法与使用的Json序列化器无关。

我们的目标是在ASP。NET Core API以及在Swagger中相同的文档。我们目前正在使用[DataContract]和[EnumMember],所以方法是从EnumMember值属性中获取小写的值,并全面使用它。

我们的示例枚举:

[DataContract]
public class enum Colors
{
  [EnumMember(Value="brightPink")]
  BrightPink,
  [EnumMember(Value="blue")]
  Blue
}

我们将使用Swashbuckle中的EnumMember值,使用缺血滤器,如下所示:

public class DescribeEnumMemberValues : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (context.Type.IsEnum)
        {
            schema.Enum.Clear();

            //Retrieve each of the values decorated with an EnumMember attribute
            foreach (var member in context.Type.GetMembers())
            {
                var memberAttr = member.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault();
                if (memberAttr != null)
                {
                    var attr = (EnumMemberAttribute) memberAttr;
                    schema.Enum.Add(new OpenApiString(attr.Value));
                }
            }
        }
    }
}

我们正在使用第三方NuGet包(GitHub repo)来确保这个命名方案也在ASP中使用。净的核心。在ConfigureServices中的Startup.cs中配置它:

services.AddControllers()
  .AddJsonOptions(opt => opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverterWithAttributeSupport()));

最后,我们需要在Swashbuckle中注册我们的缺血afilter,所以也在ConfigureServices()中添加以下内容:

services.AddSwaggerGen(c => {
  c.SchemaFilter<DescribeEnumMemberValues>();
});

其他回答

使全球

从文档中可以看出:

httpConfiguration
    .EnableSwagger(c => 
        {
            c.SingleApiVersion("v1", "A title for your API");
            
            c.DescribeAllEnumsAsStrings(); // this will do the trick
        });

特定属性的Enum/字符串转换

另外,如果你想让这种行为只发生在特定的类型和属性上,使用StringEnumConverter:

public class Letter 
{
    [Required]
    public string Content {get; set;}

    [Required]
    [EnumDataType(typeof(Priority))]
    [JsonConverter(typeof(StringEnumConverter))]
    public Priority Priority {get; set;}
}

如果你使用的是Newtonsoft和Swashbuckle v5.0.0或更高版本

你还需要这个包:

Swashbuckle.AspNetCore.Newtonsoft

在你的创业公司里:

services.AddSwaggerGenNewtonsoftSupport(); // explicit opt-in - needs to be placed after AddSwaggerGen()

这里有文档:https://github.com/domaindrivendev/Swashbuckle.AspNetCore#systemtextjson-stj-vs-newtonsoft

对于。net core 5 它与。net core 3.1相同 也就是加上

   options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());

例子:

services.AddControllers(options =>
{
    options.ReturnHttpNotAcceptable = true;
    var builder = new AuthorizationPolicyBuilder().RequireAuthenticatedUser();
    options.Filters.Add(new AuthorizeFilter(builder.Build()));
 }).AddJsonOptions(options =>
 {
    options.JsonSerializerOptions.IgnoreNullValues = true;
    options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
 });

我想我也有类似的问题。我正在寻找swagger与int ->字符串映射一起生成枚举。API必须接受整型。swagger-ui不那么重要,我真正想要的是代码生成与另一边的“真实”enum(在这种情况下使用改装的android应用程序)。

因此,从我的研究来看,这最终似乎是Swagger使用的OpenAPI规范的一个限制。不能为枚举指定名称和编号。

我发现最好的问题是https://github.com/OAI/OpenAPI-Specification/issues/681,它看起来像“可能很快”,但Swagger将不得不更新,在我的情况下Swashbuckle也是如此。

目前,我的解决方法是实现一个文档过滤器,它查找枚举,并用枚举的内容填充相关的描述。

        GlobalConfiguration.Configuration
            .EnableSwagger(c =>
                {
                    c.DocumentFilter<SwaggerAddEnumDescriptions>();

                    //disable this
                    //c.DescribeAllEnumsAsStrings()

SwaggerAddEnumDescriptions.cs:

using System;
using System.Web.Http.Description;
using Swashbuckle.Swagger;
using System.Collections.Generic;

public class SwaggerAddEnumDescriptions : 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 != null && 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 != null && paramEnums.Count > 0)
                {
                    param.description += DescribeEnum(paramEnums);
                }
            }
        }
    }

    private string DescribeEnum(IList<object> enums)
    {
        List<string> enumDescriptions = new List<string>();
        foreach (object enumOption in enums)
        {
            enumDescriptions.Add(string.Format("{0} = {1}", (int)enumOption, Enum.GetName(enumOption.GetType(), enumOption)));
        }
        return string.Join(", ", enumDescriptions.ToArray());
    }

}

这会在你的swagger-ui上产生如下的结果,这样至少你可以“看到你在做什么”:

为了生成有名称和值的枚举,可以使用此解决方案。

先决条件:

你正在使用NSwag或Openapi-generator来生成API客户端 你有一个旧的Web Api项目(pre . net Core)并使用Swashbuckle。WebApi包

SchemaFilter登记:

GlobalConfiguration.Configuration
    .EnableSwagger("/swagger", c =>
    {
        c.SchemaFilter<EnumSchemaFilter>();
    });

EnumSchemaFilter:

public class EnumSchemaFilter : ISchemaFilter
{
    public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
    {
        var enumProperties = schema.properties?.Where(p => p.Value.@enum != null);
        if(enumProperties != null)
        {
            foreach (var property in enumProperties)
            {
                var array = Enum.GetNames(type.GetProperty(property.Key).PropertyType).ToArray();
                property.Value.vendorExtensions.Add("x-enumNames", array); // NSwag
                property.Value.vendorExtensions.Add("x-enum-varnames", array); // Openapi-generator
            }
        }
    }
}

.NET CORE 3.1和SWAGGER 5

如果你需要一个简单的解决方案来选择性地使枚举作为字符串传递:

using System.Text.Json.Serialization;


[JsonConverter(typeof(JsonStringEnumConverter))]
public enum MyEnum
{
    A, B
}

注意,我们使用System.Text.Json.Serialization命名空间,而不是Newtonsoft.Json!