使用 ASP.NET Core Web API 在 Swashbuckle 6 (Swagger) 中重命名模型
Rename model in Swashbuckle 6 (Swagger) with ASP.NET Core Web API
我将 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);
}
想通了...类似于此处的答案:
唯一的区别是 属性 现在称为 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 也可以解决这个问题。
步骤:
- 像@ultravelocity 那样添加 customSchemaId-Strategy
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;
}
我将 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);
}
想通了...类似于此处的答案:
唯一的区别是 属性 现在称为 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 也可以解决这个问题。
步骤:
- 像@ultravelocity 那样添加 customSchemaId-Strategy
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;
}