如何使用 Nswag 为我的 API DTO(基于生成器)指定不同的名称?

S. *_*nke 6 c# asp.net-core openapi nswag nswagstudio

我有一个 .NET 5.0 ASP.NET Core 项目,我正在使用它Nswag来生成 API 客户端。假设我有以下 API 模型:

public class GetFooListResponseModel
{
    public string Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想要的是两件事。让我们从基本的开始。

  • 如何使生成的 API 客户端模型名称与我的项目中的模型名称不同?例如,我希望调用生成的打字稿模型而Foo不是GetFooListResponseModel.
  • 我可以根据它生成的客户端让它们具有不同的名称吗?例如,对于我的 C# 客户端,我完全可以接受现有的模型名称,但需要更改打字稿名称。如果这是不可能的,那也没什么大不了的,但那就太好了。

非常感谢!

小智 5

您可以使用 SchemaNameGenerator 自定义模型名称。你可以参考shadowsheep的回答。要生成全新的模型名称,您可以将 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

具有 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; }
}
Run Code Online (Sandbox Code Playgroud)

更新配置服务

services.AddSwaggerDocument(cfg => { cfg.SchemaNameGenerator = new CustomSchemaNameGenerator(); });
Run Code Online (Sandbox Code Playgroud)

swagger.json

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


Vin*_*Lim -1

您可以简单地创建一个名为“FooService”的可注入服务,用于使用 HTTP 请求与后端服务进行通信。指定从 API 返回的模型/类(您可以创建任何您想要的名称)getFooListResponse()。不必要的命名必须与 相同GetFooListResponseModel,只要模型/类的属性及其数据类型相同即可。

foo.service.ts

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

  getFooListResponse() {
    const endpointUrl = "myEndpointUrl";
    return this.http.get<Foo>(endpointUrl);
  }
}
Run Code Online (Sandbox Code Playgroud)

foo.model.ts

export class Foo {
    public Bar: string;
}
Run Code Online (Sandbox Code Playgroud)