簡體   English   中英

如何使用 Nswag 為我的 API DTO(基於生成器)設置不同的名稱?

[英]How to have different names for my API DTO's (based on the generator) with Nswag?

我有一個 .NET 5.0 ASP.NET 核心項目,我正在使用Nswag生成一個 API 客戶端。 假設我有以下 API model:

public class GetFooListResponseModel
{
    public string Bar { get; set; }
}

我想要的是兩件事。 讓我們從基本的開始。

  • 如何使生成的 API 客戶端的 model 名稱與我項目中的名稱不同? 例如,我希望將生成的 typescript model 稱為Foo而不是GetFooListResponseModel
  • 我可以根據它生成的客戶端使它們具有不同的名稱嗎? 例如,對於我的 C# 客戶端,我完全可以使用現有的 model 名稱,但需要更改 typescript 名稱。 如果這是不可能的,那沒什么大不了的,但這會很好。

非常感謝!

您可以使用 SchemaNameGenerator 自定義 model 名稱。 你可以參考shadowsheep的回答。 要生成全新的 Model 名稱,您可以將 CustomeAttribute 與 SchemaNameGenerator 一起使用。

public class ClientModelAttribute : Attribute
{
    public string Name { get; set; }
    public ClientModelAttribute(string name)
    {
        Name = name;
    }
}

  internal class CustomSchemaNameGenerator : ISchemaNameGenerator
{
    public string Generate(Type type)
    {
        var attrs = type.GetCustomAttributes(typeof(ClientModelAttribute),true);

        foreach (var attr in attrs)
        {
            if(attr is ClientModelAttribute)
            {
                ClientModelAttribute clientModel = attr as ClientModelAttribute;
                return clientModel.Name;
            }
        }

        return type.FullName;
    }
}

Model Class 與 CustomAttribute

[ClientModel("Foo")]
public class WeatherForecast
{
    public DateTime Date { get; set; }

    public int TemperatureC { get; set; }

    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

    public string Summary { get; set; }
}

更新配置服務

services.AddSwaggerDocument(cfg => { cfg.SchemaNameGenerator = new CustomSchemaNameGenerator(); });

swagger.json

 "paths": {
"/WeatherForecast": {
  "get": {
    "tags": [
      "WeatherForecast"
    ],
    "operationId": "WeatherForecast_Get",
    "responses": {
      "200": {
        "x-nullable": false,
        "description": "",
        "schema": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/Foo"
          }
        }
      }
    }
  }
}

您可以使用 HTTP 請求簡單地創建一個名為“FooService”的可注入服務,用於與后端服務通信。 getFooListResponse() 不必命名必須與GetFooListResponseModel相同,只要模型/類的屬性及其數據類型相同即可。

foo.service.ts

@Injectable()
export class FooService 
{
  constructor(
  protected http: HttpClient
  ) {}

  getFooListResponse() {
    const endpointUrl = "myEndpointUrl";
    return this.http.get<Foo>(endpointUrl);
  }
}

foo.model.ts

export class Foo {
    public Bar: string;
}

有時,最好的解決方案是最簡單的。 嘗試創建一個窗口/消息,詢問用戶他們希望他們的模塊名稱是什么,一旦程序啟動就會觸發?

暫無
暫無

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

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