簡體   English   中英

使用 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; }
}

如何在生成的文檔中將其重命名為“測試”? 我試過添加一個帶有名稱的 DataContract 屬性,但這沒有幫助。

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

想出來了......類似於這里的答案: 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;
}

@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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM