繁体   English   中英

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

[英]Swashbuckle rename Data Type in Model

我正在整理一个需要匹配外部源 XML 格式的 Web API,并希望在 swagger 输出中重命名数据类型对象。

它在类的成员上运行良好,但我想知道是否也可以覆盖类名。

例子:

[DataContract(Name="OVERRIDECLASSNAME")]
public class TestItem
{
   [DataMember(Name="OVERRIDETHIS")]
   public string toOverride {get; set;}
}

在生成的输出中,我最终看到了模型:

   TestItem {
      OVERRIDETHIS (string, optional)
   }

我希望看到

OVERRIDECLASSNAME { OVERRIDETHIS(字符串,可选)}

这可能吗?

谢谢,

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

首先在 Swagger 配置中添加 SchemaId(从 5.2.2 版开始,请参阅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;
}

希望能帮助到你。

很老的问题,但是当我正在寻找类似的解决方案时,我遇到了这个问题。 我认为文森特答案中的代码可能不起作用。 这是我的看法:

    private static string schemaIdStrategy(Type currentClass)
    {
        var dataContractAttribute = currentClass.GetCustomAttribute<DataContractAttribute>();
        return dataContractAttribute != null && dataContractAttribute.Name != null ? dataContractAttribute.Name : currentClass.Name;
    }

添加到线程,因为我无法将答案与 Swashbukle 用于 AspNetCore。 我正在这样做。 但是,我并不完全高兴,好像该对象包含在另一个显示其原始名称的对象中。 例如,如果您有一个分页的结果集,结果显示不正确。所以这不是最终答案,但可能适用于简单的用例。

我正在使用架构过滤器。 当我获取数据类型的 Title 属性时,对象只有 [JsonObject(Title="CustomName")]。 首先定义一个这样的类:

public class CustomNameSchema : ISchemaFilter
    {
        public void Apply(Schema schema, SchemaFilterContext context)
        {
            if (schema?.Properties == null)
            {
                return;
            }

            var objAttribute = context.SystemType.GetCustomAttribute<JsonObjectAttribute>();
            if( objAttribute!= default && objAttribute?.Title?.Length > 0)
            {
                schema.Title = objAttribute.Title;
            }
        }
    }

在启动时,您必须配置一个 SchemaFilter

c.SchemaFilter<CustomNameSchema>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM