![](/img/trans.png)
[英]How to bind entity, that I have got from database, to my request's 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; }
}
我想要的是兩件事。 讓我們從基本的開始。
Foo
而不是GetFooListResponseModel
。非常感謝!
您可以使用 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.