Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwashBuckle/Swagger is hiding my immutable properties

For models that get passed into actions via [FromBody] I like to make their properties immutable public int SomeProperty { get; private set; }. This way I know the input to my handler isn't modified.

The problem I'm having is that Swagger and Swashbuckle are completely ignoring those fields for rendering examples of parameter payloads. I looked at the swagger schema that was generated from our API and saw that all of the mentioned fields have readOnly: true.

I'm wondering if there is some way to configure Swashbuckler or Swagger to not ignore these properties. Or maybe there is some way to just set readonly to false for each definition using some part of SwashBuckle's extension framework?

Edit: Adding sample from swagger.json

On this example someProperty is marked readOnly. I think that is why the property doesn't show up in the generated example of a POST parameter. If there is a way to make swagger gen not add any readonly properties I'd be fine with that.

{
  "type": "object",
  "properties": {
    "someProperty": {
      "format": "int32",
      "type": "integer",
      "readOnly": true
    },
  }
}
like image 275
rocktheartsm4l Avatar asked May 11 '19 06:05

rocktheartsm4l


1 Answers

So I found a solution. I created an ISchemaFilter implementation that just sets readonly on each property to false. I need to think more about what this implies downstream, so I'm not sure if I like the solution yet.

public class IgnoreReadOnlySchemaFilter : ISchemaFilter
{
    public void Apply(Schema schema, SchemaFilterContext context)
    {
        schema.ReadOnly = false;
        if (schema.Properties != null)
        {
            foreach (var keyValuePair in schema.Properties)
            {
                keyValuePair.Value.ReadOnly = false;
            }
        }
    }
}
like image 154
rocktheartsm4l Avatar answered Oct 29 '22 08:10

rocktheartsm4l