我正在将 Swashbuckle 6 (Swagger) 与 ASP.NET Core Web API 结合使用。我的模型有 DTO 作为后缀,例如,
public class TestDTO {
public int Code { get; set; }
public string Message { get; set; }
}
如何在生成的文档中将其重命名为“Test”?我尝试添加带有名称的 DataContract 属性,但这没有帮助。
[HttpGet]
public IActionResult Get() {
//... create List<TestDTO>
return Ok(list);
}
弄清楚了...类似于此处的答案:Swashbuckle 重命名模型中的数据类型
唯一的区别是该属性现在称为 CustomSchemaIds 而不是 SchemaId:
options.CustomSchemaIds(schemaIdStrategy);
我没有查看 DataContract 属性,而是删除了“DTO”:
private static string schemaIdStrategy(Type currentClass) {
string returnedValue = currentClass.Name;
if (returnedValue.EndsWith("DTO"))
returnedValue = returnedValue.Replace("DTO", string.Empty);
return returnedValue;
}
@ultravelocity 的答案对我来说不太有效。该错误类似于“'Response`1'已被使用”。我不知道确切的原因是什么,但我想这与继承/泛型有关(因为我返回了分页响应)。
根据@ultravelocity的问题和答案,我为.net 5(也可能为asp.net core 2.c/3.d)开发了一个可能的解决方案来解决这个问题。
步骤:
a.CustomSchemaIds(schemaIdStrategy);
private static string schemaIdStrategy(Type currentClass)
{
string customSuffix = "Response";
var tmpDisplayName = currentClass.ShortDisplayName().Replace("<", "").Replace(">", "");
var removedSuffix = tmpDisplayName.EndsWith(customSuffix) ? tmpDisplayName.Substring(0, tmpDisplayName.Length - customSuffix.Length) : tmpDisplayName;
return removedSuffix;
}
private static string DefaultSchemaIdSelector(Type modelType)
{
if (!modelType.IsConstructedGenericType) return modelType.Name.Replace("[]", "Array");
var prefix = modelType.GetGenericArguments()
.Select(genericArg => DefaultSchemaIdSelector(genericArg))
.Aggregate((previous, current) => previous + current);
return prefix + modelType.Name.Split('`').First();
}
然后像这样继续构建
options.CustomSchemaIds(type => DefaultSchemaIdSelector(type).Replace("DTO", string.Empty));