简体   繁体   English

如何在 Create 方法上设置 Swagger 忽略 id 属性? C# ASP.NET 内核 Swagger

[英]How to set Swagger ignore id property on Create method? C# ASP.NET Core Swagger

How can I ask Swagger not to ask id for POST method (creation of entity in DB)?我怎样才能要求 Swagger 不询问 POST 方法的 id(在 DB 中创建实体)?

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

There is an auto-incrementation in my SQL Server, so I think on frontend it's not necessary to input Id and there will be no field for Id.我的 SQL 服务器中有一个自动增量,所以我认为在前端不需要输入 Id 并且不会有 Id 字段。 But is it possible to ask swagger not to show id?但是是否可以要求 swagger 不显示 id?

Create a dedicated create dto:创建一个专用的create dto:

public class CreateDto {

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

and in your controller create an instance of your db entity from the incoming CreateDto object.并在您的控制器中从传入的CreateDto对象创建您的 db 实体的实例。

You could try with JsonIgnore attribute if you don't need to Serialize the model somewhere else in your project I tried as below:如果您不需要在项目中的其他地方序列化模型,您可以尝试使用 JsonIgnore 属性,我尝试如下:

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

The result:结果: 在此处输入图像描述

There is a better way now with now.现在有一个更好的方法。 There are two things you need to do你需要做两件事

  1. Annotate with SwaggerSchema found in Swashbuckle.AspNetCore.Annotations;使用 Swashbuckle.AspNetCore.Annotations 中的 SwaggerSchema 进行注释;
    [SwaggerSchema(ReadOnly = true)]
    public int Id { get; set; }
  1. EnableAnnotations in AddSwaggerGen AddSwaggerGen 中的 EnableAnnotations
    builder.Services.AddSwaggerGen(options =>
    {
        options.EnableAnnotations();
    });

See more about it in the Documentation文档中查看更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM