【问题标题】:How to set Swagger ignore id property on Create method? C# ASP.NET Core Swagger如何在 Create 方法上设置 Swagger 忽略 id 属性? C# ASP.NET Core Swagger
【发布时间】:2022-07-08 22:15:11
【问题描述】:

我怎样才能让 Swagger 不要为 POST 方法询问 id(在 DB 中创建实体)?

{
  "id": 0,
  "name": "string",
  "quantity": 0,
  "typeId": 0,
  "brandId": 0
}

我的 SQL Server 中有一个自动增量,所以我认为在前端不需要输入 Id,并且不会有 Id 字段。但是能不能让swagger不显示id呢?

【问题讨论】:

  • 生成的不是大摇大摆,而是您在 post 方法中期望的模型。通常,如果您愿意,您应该使用不带 id 的 DTO。
  • 您使用什么库/框架 - Swashbuckle、Swagger-Net 等等?检查此库是否提供注释以将属性标记为只读。 Swagger UI 不会在请求正文示例中显示只读属性。

标签: c# asp.net-core swagger


【解决方案1】:

创建一个专用的create dto:

public class CreateDto {

  public class Name { get; set;}
  public int Quantity { get; set;}
  ...
}

并在您的控制器中从传入的CreateDto 对象创建您的数据库实体的实例。

【讨论】:

  • 我需要一些从我的对象到 CreateDto 的映射器吗?它应该是什么样子?
【解决方案2】:

如果您不需要在项目的其他地方序列化模型,您可以尝试使用 JsonIgnore 属性 我尝试如下:

public class TestModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        [JsonIgnore]
        public string Hide { get; set; }
    }

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2022-11-18
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多