且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swashbuckle 重命名模型中的数据类型

更新时间:2023-12-01 22:33:10

我有同样的问题,我想我现在解决了.

I had the same problem and I think I solved it now.

首先在 Swagger 配置中添加 SchemaId(从版本 5.2.2 见 https://github.com/domaindrivendev/Swashbuckle/issues/457):

First of all add SchemaId in Swagger Configuration (from version 5.2.2 see https://github.com/domaindrivendev/Swashbuckle/issues/457):

GlobalConfiguration.Configuration
    .EnableSwagger(c =>
    {
        c.SchemaId(schemaIdStrategy);
        [...]
    }

然后添加这个方法:

private static string schemaIdStrategy(Type currentClass)
{
    string returnedValue = currentClass.Name;
    foreach (var customAttributeData in currentClass.CustomAttributes)
    {
        if (customAttributeData.AttributeType.Name.ToLower() == "datacontractattribute")
        {
            foreach (var argument in customAttributeData.NamedArguments)
            {
                if (argument.MemberName.ToLower() == "name")
                {
                    returnedValue = argument.TypedValue.Value.ToString();
                }
            }
        }
    }
    return returnedValue;
}

希望对你有帮助.