【问题标题】:How to configure Swashbuckle to ignore property on model differently for request and response如何配置 Swashbuckle 以针对请求和响应以不同方式忽略模型上的属性
【发布时间】:2020-04-08 22:10:47
【问题描述】:

这里提到了我找到的最接近的参考,它非常有效。 How to configure Swashbuckle to ignore property on model

但是,如果我们可以在同一模型上显示/隐藏请求和响应的不同属性,有没有办法?目前,提供的解决方案为请求和响应隐藏了相同的属性。这方面的一个例子是,当我们有 ID 字段时,我们不想在 Swagger 中显示请求,并且在响应时使用可用的 ID 创建记录。

我能想到的另一种选择是构建一个不同的模型,但代码冗余太可怕了。

【问题讨论】:

标签: c# asp.net-core swagger swashbuckle


【解决方案1】:

也许您可以隐藏定义,但无论如何都会发送数据。 使用 ISchemaFilter 可以删除一些对象属性。

User:
    type: "object"
    properties:
      id:
        type: "integer"
        format: "int64"
      username:
        type: "string"
      firstName:
        type: "string"
      lastName:
        type: "string"
      email:
        type: "string"
      password:
        type: "string"
      phone:
        type: "string"
      userStatus:
        type: "integer"
        format: "int32"
        description: "User Status"

但你不能为所欲为!

/user:
    post:
      tags:
      - "user"
      summary: "Create user"
      description: "This can only be done by the logged in user."
      operationId: "createUser"
      produces:
      - "application/xml"
      - "application/json"
      parameters:
      - in: "body"
        name: "body"
        description: "Created user object"
        required: true
        schema:
          $ref: "#/definitions/User" <--here !!!
      responses:
        200:
          description: "successful operation"
          schema:
            $ref: "#/definitions/User" <--here !!!
        400:
          description: "Invalid username supplied"
        404:
          description: "User not found"

那些输入和输出指向同一个对象

/user/post/parameters[0]/schema/ref
/user/post/responses/200/schema/ref

你不能为一个对象做两个定义。

但是你可以使用继承和隐藏。

public class All 
{
    public string test { get; set; }
    public string test2 { get; set; }
}

public class Some : All
{
    private new string test { get; set; }
    protected new string test2 { get { return base.test2; } set { base.test2 = value; } }
}

C2 x = new C2();
C1 y = x;
x.test = "xx";

System.Console.WriteLine(x.test); // "xx"
System.Console.WriteLine(y.test); // empty


System.Console.WriteLine(x.test2); // "xx"
System.Console.WriteLine(y.test2); // "xx"

【讨论】:

    猜你喜欢
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 2012-06-18
    • 2019-06-16
    • 2019-01-20
    相关资源
    最近更新 更多