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

2023-09-08 09:25:29 作者:不知该叫啥~

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

I'm using Swashbuckle 6 (Swagger) with ASP.NET Core Web API. My models have DTO as a suffix, e.g.,

public class TestDTO {
    public int Code { get; set; }
    public string Message { get; set; }
}

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

How do I rename it to just "Test" in the generated documentation? I've tried adding a DataContract attribute with a name, but that didn't help.

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

推荐答案

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

Figured it out... similar to the answer here: Swashbuckle rename Data Type in Model

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

The only difference was the property is now called CustomSchemaIds instead of SchemaId:

options.CustomSchemaIds(schemaIdStrategy);

我没有查看 DataContract 属性,而是将其删除DTO":

Instead of looking at the DataContract attribute, I just have it remove "DTO":

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