gpt4 book ai didi

c# - 是否可以在不使用 [JsonIgnore] 的情况下忽略 nswag 中的模型属性?

转载 作者:行者123 更新时间:2023-12-04 15:39:47 24 4
gpt4 key购买 nike

在我的项目中无法使用 JsonIgnore,并且 [OpenApiIgnore] 不起作用。在 swashbuckle 中可以通过它自己的属性来制作过滤器,但是在 NSwag 中我没有找到类似的机制。

代码示例:

API 网关上的命令类:

[MessageNamespace("identity")]
public class UpdateUser:ICommand
{
[JsonConstructor]
public UpdateUser(string surname, string name, string middleName, string department, string position, string adAccount, string email, string userName, string password)
{
Surname = surname;
Name = name;
MiddleName = middleName;
Department = department;
Position = position;
AdAccount = adAccount;
Email = email;
UserName = userName;
}
[JsonIgnore]
public Guid Id { get; }

...

}

微服务上的命令类:

 public class UpdateUser:ICommand
{
[JsonConstructor]
public UpdateUser(Guid id, string surname, string name, string middleName, string department, string position, string adAccount, string email, string userName, string password)
{
Id = id;
Surname = surname;
Name = name;
MiddleName = middleName;
Department = department;
Position = position;
AdAccount = adAccount;
Email = email;
UserName = userName;
}

public Guid Id { get; }
...

}

网关上的Api方法:

[HttpPut("{id}")]
[JwtAuth(Roles.Administrator)]
public async Task<ActionResult> Put(Guid id, UpdateUser command)
{
//Send command to RabbitMQ(serialized)
//Id binded before sending but after construct in service ID is missing
await SendAsync(command.Bind(c => c.Id, id));
return Accepted();
}

为什么我需要从 NSwag 生成中删除属性?因为我在路由中需要 Id,但如果 Id 也位于查询正文中,它会使我的前端编码器具有侵略性和破坏性 хD,而且它也不漂亮: nswag generation

最佳答案

我的解决方案是使用单独的类

namespace API.Models
{
public class UpdateUser
{
public string Surname { get; set; }
public string Name { get; set; }
...
}
}

namespace Domain.Commands
{
public class UpdateUser:ICommand
{
[JsonConstructor]
public UpdateUser(Guid id, string surname, string name, string middleName, string department, string position, string adAccount, string email, string userName, string password)
{
Id = id;
Surname = surname;
Name = name;
MiddleName = middleName;
Department = department;
Position = position;
AdAccount = adAccount;
Email = email;
UserName = userName;
}

public Guid Id { get; }
...

}
}

在 Controller 中

namespace API.Controllers
{
public class UserController
{
[HttpPut("{id}")]
[JwtAuth(Roles.Administrator)]
public async Task<ActionResult> Put(Guid id, API.Models.UpdateUser command)
{
//Send command to RabbitMQ(serialized)
//Id binded before sending but after construct in service ID is missing
var cmd = new Domain.Commands.UpdateUser( id, command.Surname, command.Name, ... );

await SendAsync(cmd);
return Accepted();
}
}
}

Domain.Commands 可以放在类库中,也可以被 API 和微服务使用。

关于c# - 是否可以在不使用 [JsonIgnore] 的情况下忽略 nswag 中的模型属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58196772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com