How to configure Swashbuckle to ignore property on model

后端 未结 15 1773
旧巷少年郎
旧巷少年郎 2020-12-02 15:10

I\'m using Swashbuckle to generate swagger documentation\\UI for a webapi2 project. Our models are shared with some legacy interfaces so there are a couple of properties I

15条回答
  •  猫巷女王i
    2020-12-02 15:51

    In my case I wanted to keep my Application Layer DTOs clean (without any annotation like JsonIngore) but still being able to use them in my Controllers Web APIs.

    So, in my Application Layer I have a DTO like this:

    public class CreateItemCommand {
         public Guid ContainerId { get; set; }
         public string Name { get; set; }
    }
    

    And my API design for creating an item is something like: POST /containers/{containerId}/items

    As the ContainerId is coming from the api route, I don't want the asp.net core trying to bind it into the command DTO and I don't want swashbuckle listing it neither.

    So my solution is to inherit the original DTO in the API layer like this:

    public class CreateItemCommandMod : CreateItemCommand {
       #pragma warning disable IDE0051
       private new ContainerID { get; }
       #pragma warning restore IDE0051
    }
    
    ...
    
    [HttpPost("{containerId}/items}")]
    public Task Create(
       [FromRoute] Guid containerId,
       [FromBody] CreateItemCommandMod command,
    ) => useCase.Create(command.Apply(r => r.ContainerId = containerId));
    
    • The useCase.Create from the ApplicationLayer expects the base class CreateItemCommand.
    • .Apply is just a very simple extension method that i've made to easily set the routing parameter value into the correspondent dto property.

提交回复
热议问题