我正在整理一个需要匹配外部源XML格式的Web API,并且希望在swagger输出中重命名数据类型对象。
它对班级成员工作正常,但我想知道是否有可能覆盖班级名称。
示例:
[DataContract(Name="OVERRIDECLASSNAME")]
public class TestItem
{
[DataMember(Name="OVERRIDETHIS")]
public string toOverride {get; set;}
}
在生成的输出中,我最终看到了 型号:
TestItem {
OVERRIDETHIS (string, optional)
}
我希望看到
OVERRIDECLASSNAME { OVERRIDETHIS(字符串,可选) }
这可能吗?
谢谢,
答案 0 :(得分:0)
我遇到了同样的问题,我想我现在已经解决了。
首先在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;
}
希望它有所帮助。
答案 1 :(得分:0)
一个相当老的问题,但是当我在寻找类似的解决方案时,我碰到了这个问题。 我认为文森特答案中的代码可能无法正常工作。 这是我的看法:
private static string schemaIdStrategy(Type currentClass)
{
var dataContractAttribute = currentClass.GetCustomAttribute<DataContractAttribute>();
return dataContractAttribute != null && dataContractAttribute.Name != null ? dataContractAttribute.Name : currentClass.Name;
}
答案 2 :(得分:0)
添加到线程中,因为我无法将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>();