【问题标题】:Rename model in Swashbuckle 6 (Swagger) with ASP.NET Core Web API使用 ASP.NET Core Web API 重命名 Swashbuckle 6 (Swagger) 中的模型
【发布时间】:2016-11-16 23:18:13
【问题描述】:

我正在使用带有 ASP.NET Core Web API 的 Swashbuckle 6 (Swagger)。我的模型以 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


    【解决方案1】:

    想通了...类似于这里的答案:Swashbuckle rename Data Type in Model

    唯一的区别是该属性现在称为 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;
    }
    

    【讨论】:

    • 这是一个非常有帮助的答案。
    • 一个快速的内联解决方案可能是 c.CustomSchemaIds(type => type.Name.EndsWith("DTO") ? type.Name.Replace("DTO", string.Empty) : type.Name );
    • 告诉我如何从 EFCore 生成的类中删除“tbl”。谢谢@ultravelocity!
    【解决方案2】:

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

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

    步骤:

    1. 像 @ultralocity 那样添加 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 2015-11-07
      • 2018-07-29
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多