Autorest + Swagger未正确生成ENUM

r6hnlfcb  于 2022-11-06  发布在  其他
关注(0)|答案(4)|浏览(180)

我有两个应用程序AB。在A上,我使用swagger来描述API。在A上,我也有一些枚举属性的类的定义。我想在B上生成一个客户端API。为此,我使用Autorest。除了一件事-枚举之外,一切都正常。由于某种原因,枚举没有正确生成,并且一种属性(最初是枚举)是string或int类型(取决于 DescribeAllEnumsAsStrings() 的使用。我在下面的示例中使用了它,因此在本例中它是string)。
枚举定义由swagger生成的JSON:

"Car": {
        "properties": {
            "color": {
                "enum": [
                    "Red",
                    "Blue",
                    "Green"
                ],
                "type": "string"
            }
        },
        "type": "object"
    }

Startup.cs中的晃动注册

// Register the Swagger generator, defining one or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "Car API", Version = "v1" });
            c.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description = "description", Name = "Authorization", Type = "apiKey" });
            c.DescribeAllEnumsAsStrings();
        });

自动复位命令:

autorest --input-file=http://localhost:55448/swagger/v1/swagger.json --csharp --namespace=Online.Integrations.Api.Service.Car --output-folder=.

生成的类(字符串而不是枚举):

public partial class Car
{
    /// <summary>
    /// Initializes a new instance of the Car class.
    /// </summary>
    public Car()
    {
      CustomInit();
    }

    /// <summary>
    /// Initializes a new instance of the Car class.
    /// </summary>
    /// <param name="application">Possible values include: 'Any', 'Web'
    /// ...
    /// </param>
    public Car(string color = default(string))
    {
        Color = color;
    }

    /// <summary>
    /// An initialization method that performs custom operations like setting defaults
    /// </summary>
    partial void CustomInit();

    /// <summary>
    /// </summary>
    [JsonProperty(PropertyName = "color")]
    public string Color { get; set; }
}

我发现了这个:https://github.com/Azure/autorest/tree/master/docs/extensions#x-ms-enum
有一些x-ms-enum扩展,但我不知道如何使用它。我尝试手动编辑JSON定义(我在下面的示例中所做的),但也不成功。生成的类包含 object color = default(object) 而不是第一个示例中的字符串,不是枚举。

"color": {
            "type": "string",
            "enum": [
                "Red",
                "Blue",
                "Green"
            ],
            "x-ms-enum": {
                "name": "Color",
                "modelAsString": false
     },

我会很高兴的任何帮助。谢谢!
编辑:1)完全摆动定义(结果类型:叮):

  • 在swagger定义中,“类型”为:枚举定义后面的“string”*
{"swagger":"2.0","info":{"version":"v1","title":"Audit Overseer API"},"basePath":"/","paths":{"/api/Audit":{"get":{"tags":["Audit"],"operationId":"ApiAuditGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"Id","in":"query","required":false,"type":"string"},{"name":"Application","in":"query","required":false,"type":"string","enum":["Any","Alfa","Beta"]},{"name":"DatabaseName","in":"query","required":false,"type":"string"}],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/Transaction"}}}}}}},"definitions":{"Transaction":{"type":"object","properties":{"callId":{"type":"string"},"actionName":{"type":"string"},"application":{"enum":["Any","Alfa","Beta"],"type":"string"},"httpStatusCode":{"type":"string"},"dateTime":{"format":"date-time","type":"string"}}}},"securityDefinitions":{"Bearer":{"name":"Authorization","in":"header","type":"apiKey","description":"Please insert JWT with Bearer into field"}}}

自动复位执行:
x1c 0d1x结果:

2)全摆动定义(结果类型:对象):

  • 在swagger def.我的实验中,“x-ms-enum”就在枚举定义之后 *
{"basePath":"/","definitions":{"Transaction":{"properties":{"actionName":{"type":"string"},"application":{"enum":["Any","Alfa","Beta"],"x-ms-enum":{"modelAsString":false,"name":"Application"}},"callId":{"type":"string"},"dateTime":{"format":"date-time","type":"string"},"httpStatusCode":{"type":"string"}},"type":"object"}},"info":{"title":"Audit Overseer API","version":"v1"},"paths":{"/api/Audit":{"get":{"consumes":[],"operationId":"ApiAuditGet","parameters":[{"in":"query","name":"Id","required":false,"type":"string"},{"enum":["Any","Alfa","Beta"],"in":"query","name":"Application","required":false,"type":"string"},{"in":"query","name":"DatabaseName","required":false,"type":"string"}],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"items":{"$ref":"#/definitions/Transaction"},"type":"array"}}},"tags":["Audit"]}}},"securityDefinitions":{"Bearer":{"description":"Please insert JWT with Bearer into field","in":"header","name":"Authorization","type":"apiKey"}},"swagger":"2.0"}
  • ...也可以空着,结果一样 *
{"basePath":"/","definitions":{"Transaction":{"properties":{"actionName":{"type":"string"},"application":{"enum":["Any","Alfa","Beta"]},"callId":{"type":"string"},"dateTime":{"format":"date-time","type":"string"},"httpStatusCode":{"type":"string"}},"type":"object"}},"info":{"title":"Audit Overseer API","version":"v1"},"paths":{"/api/Audit":{"get":{"consumes":[],"operationId":"ApiAuditGet","parameters":[{"in":"query","name":"Id","required":false,"type":"string"},{"enum":["Any","Alfa","Beta"],"in":"query","name":"Application","required":false,"type":"string"},{"in":"query","name":"DatabaseName","required":false,"type":"string"}],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"items":{"$ref":"#/definitions/Transaction"},"type":"array"}}},"tags":["Audit"]}}},"securityDefinitions":{"Bearer":{"description":"Please insert JWT with Bearer into field","in":"header","name":"Authorization","type":"apiKey"}},"swagger":"2.0"}
  • (现在执行与之前相同的autorest命令)*

结果为:

6uxekuva

6uxekuva1#

看起来您可以通过使用SchemaFilter<TFilter>选项方法使SwaggerGen自动添加x-ms-enum扩展。
在Startup.cs中进行Swagger注册

// Register the Swagger generator, defining one or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "Car API", Version = "v1" });
            c.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description = "description", Name = "Authorization", Type = "apiKey" });
            c.ApplyFiltersToAllSchemas();//ignore deprecation warning
            c.SchemaFilter<EnumFilter>();
            c.DescribeAllEnumsAsStrings();
        });

然后使用以下代码定义EnumFilter

public class EnumFilter : ISchemaFilter
{
    public void Apply(Schema model, SchemaFilterContext context)
    {
        if (model == null)
            throw new ArgumentNullException("model");

        if (context == null)
            throw new ArgumentNullException("context");

        if (context.SystemType.IsEnum)
            model.Extensions.Add("x-ms-enum", new
            {
                name = context.SystemType.Name,
                modelAsString = false
            });
    }
}
hc2pp10m

hc2pp10m2#

找了几个小时才找到可空枚举的解决方案!

public class EnumFilter : ISchemaFilter
{

    public void Apply(Schema model, SchemaRegistry schemaRegistry, Type type)
    {
        if (model == null)
        {
            throw new ArgumentNullException("model");
        }

        if (schemaRegistry == null)
        {
            throw new ArgumentNullException("schemaRegistry");
        }

        if (IsEnum(type, out var enumName))
        {
            model.vendorExtensions.Add("x-ms-enum", new
                                              {
                                                  name = enumName ?? type.Name,
                                                  modelAsString = false
                                              });

        }
    }

    public static bool IsEnum(Type t, out string enumName)
    {
        if (t.IsEnum)
        {
            enumName = t.Name;
            return true;
        }
        Type u = Nullable.GetUnderlyingType(t);
        enumName = u?.Name;
        return (u != null) && u.IsEnum;
    }
}
bwleehnv

bwleehnv3#

未来的校对解决方案,进一步到@richard-mcdaniel解决方案,一旦未完成的enum values issue on the autorest repo得到了修复,这里的enums部分的值就到了EnumFilter:ISchemaFilter
在Startup.cs中进行Swagger注册

// Register the Swagger generator, defining one or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "Car API", Version = "v1" });
            c.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description = "description", Name = "Authorization", Type = "apiKey" });
            c.ApplyFiltersToAllSchemas();//ignore deprecation warning
            c.SchemaFilter(() => new EnumTypeSchemaFilter(false));
            c.DescribeAllEnumsAsStrings();
        });

然后使用以下代码定义EnumFilter类:

using Swashbuckle.Swagger;
using System;

namespace Swashbuckle.AutoRestExtensions
{
    public class EnumTypeSchemaFilter : ISchemaFilter
    {
        public EnumTypeSchemaFilter()
        {
        }

        public EnumTypeSchemaFilter(bool modelAsString)
        {
            _modelAsString = modelAsString;
        }

        public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
        {
            type = Nullable.GetUnderlyingType(type) ?? type;
            System.Diagnostics.Debug.WriteLine(type.FullName);
            if (type.IsEnum)
            {
                // Add enum type information once
                if (schema.vendorExtensions.ContainsKey("x-ms-enum")) return;

                if (_modelAsString)
                {
                    schema.vendorExtensions.Add("x-ms-enum", new
                    {
                        name = type.Name,
                        modelAsString = _modelAsString
                    });
                }
                else
                {
                    var valuesList = new System.Collections.Generic.List<object>();
                    foreach (var fieldInfo in type.GetFields())
                    {
                        if (fieldInfo.FieldType.IsEnum)
                        {
                            var fName = fieldInfo.Name;
                            var fValue = (int)fieldInfo.GetRawConstantValue();
                            valuesList.Add(new { value = fValue, description = fName, name = fName });
                        }
                    }
                    schema.vendorExtensions.Add("x-ms-enum", new
                    {
                        name = type.Name,
                        modelAsString = _modelAsString,
                        values = valuesList
                        //Values:
                        /*
                        accountType:
                          type: string
                          enum:
                          - Standard_LRS
                          - Standard_ZRS
                          - Standard_GRS
                          - Standard_RAGRS
                          - Premium_LRS
                          x-ms-enum:
                            name: AccountType
                            modelAsString: false
                            values:
                            - value: Standard_LRS
                              description: Locally redundant storage.
                              name: StandardLocalRedundancy
                            - value: Standard_ZRS
                              description: Zone-redundant storage.
                            - value: Standard_GRS
                              name: StandardGeoRedundancy
                            - value: Standard_RAGRS
                            - value: Premium_LRS
                        */
                    });
                }
            }
        }

        private readonly bool _modelAsString;
    }
}
xzv2uavs

xzv2uavs4#

我用那套招摇过市的装置修好了

services.AddSwaggerGenNewtonsoftSupport();
services.AddSwaggerGen(x => x.UseInlineDefinitionsForEnums());

相关问题