如何将Swagger设置为忽略创建方法上的ID属性? C#ASP.NET核心招摇

发布于 2025-02-13 16:06:54 字数 236 浏览 0 评论 0原文

我该如何要求Swagger不要要求ID进行邮政方法(在DB中创建实体)?

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

我的SQL Server中有一个自动介入,因此我认为在Frontend上没有必要输入ID,并且ID不会有字段。但是,是否可以要求Swagger不要显示ID?

How can I ask Swagger not to ask id for POST method (creation of entity in 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. But is it possible to ask swagger not to show id?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

勿忘初心 2025-02-20 16:07:51

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

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

结果:

You could try with JsonIgnore attribute if you don't need to Serialize the model somewhere else in your project
I tried as below:

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

The result:
enter image description here

我只土不豪 2025-02-20 16:07:49

创建一个专用的Create DTO:

public class CreateDto {

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

在您的控制器中创建一个从传入的Create To To对象创建DB实体的实例。

Create a dedicated 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.

折戟 2025-02-20 16:07:43

现在有一种更好的方法。 您需要做两件事

  1. 在swashbuckle.aspnetcore.annotations中找到的swaggerschema,
    [SwaggerSchema(ReadOnly = true)]
    public int Id { get; set; }
  1. 。 AddSwaggergen中的EnableAnnotations
    builder.Services.AddSwaggerGen(options =>
    {
        options.EnableAnnotations();
    });

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;
    [SwaggerSchema(ReadOnly = true)]
    public int Id { get; set; }
  1. EnableAnnotations in AddSwaggerGen
    builder.Services.AddSwaggerGen(options =>
    {
        options.EnableAnnotations();
    });

See more about it in the Documentation

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文