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

ult*_*ity 6 c# swagger swashbuckle asp.net-core asp.net-core-webapi

我正在使用Swashbuckle 6(Swagger)和ASP.NET Core Web API.我的模型有DTO作为后缀,例如,

public class TestDTO {
    public int Code { get; set; }
    public string Message { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如何在生成的文档中将其重命名为"Test"?我已经尝试添加带有名称的DataContract属性,但这没有帮助.

[HttpGet]
public IActionResult Get() {
  //... create List<TestDTO>
  return Ok(list);
}
Run Code Online (Sandbox Code Playgroud)

ult*_*ity 12

想出来......类似于这里的答案:Swashbuckle重命名模型中的数据类型

唯一的区别是该属性现在称为CustomSchemaIds而不是SchemaId:

options.CustomSchemaIds(schemaIdStrategy);
Run Code Online (Sandbox Code Playgroud)

我没有查看DataContract属性,只是删除了"DTO":

private static string schemaIdStrategy(Type currentClass) {
    string returnedValue = currentClass.Name;
    if (returnedValue.EndsWith("DTO"))
        returnedValue = returnedValue.Replace("DTO", string.Empty);
    return returnedValue;
}
Run Code Online (Sandbox Code Playgroud)

  • 快速内联解决方案可能是 c.CustomSchemaIds(type =&gt; type.Name.EndsWith("DTO") ? type.Name.Replace("DTO", string.Empty) : type.Name); (4认同)