使用 ASP.NET Core Web API 重命名 Swashbuckle 6 (Swagger) 中的模型

问题描述 投票:0回答:3

我正在将 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);
}
c# asp.net-core swagger asp.net-core-webapi swashbuckle
3个回答
41
投票

弄清楚了...类似于此处的答案: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;
}

2
投票

@ultravelocity 的答案对我来说不太有效。该错误类似于“'Response`1'已被使用”。我不知道确切的原因是什么,但我想这与继承/泛型有关(因为我返回了分页响应)。

根据@ultravelocity的问题和答案,我为.net 5(也可能为asp.net core 2.c/3.d)开发了一个可能的解决方案来解决这个问题。

步骤:

  1. 像 @ultravelocity 一样添加 customSchemaId-Strategy
a.CustomSchemaIds(schemaIdStrategy);
  1. 添加您的自定义策略功能
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;
}

0
投票

如果有人只想更改默认架构 ID,他们可以使用此实现

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));
© www.soinside.com 2019 - 2024. All rights reserved.