简体   繁体   中英

How to configure Swashbuckle to ignore property on model differently for request and response

The closest reference to this that I found is mentioned here, which works perfectly. How to configure Swashbuckle to ignore property on model

However, is there a way if we can show/hide different properties for request and response on the same model? Currently, the solution provided hides the same properties for both request and response. An example for this is when we have ID fields where on request, we do not want to show in Swagger, and upon response the record is created with an ID available.

Another alternative that I can think of is to construct a different model, but code redundancy is horrible.

Probably you can hide definition but data will be send anyway. With use of ISchemaFilter you can remove some object properties.

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"

But you cant do what you want!

/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"

Those input and a output are pointing to same object

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

You cant do two definitions for one object.

But you can use inheritance and hiding.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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