且构网

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

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

更新时间:2023-12-01 22:45:46

我遇到了同样的问题,我想现在已经解决了.

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;
}

希望有帮助.