1

This is an extension of

Json conversion in ASP.NET for CQRS

Whereby we created a class to handle optional null-able parameters for our API.

Now I want the swagger doc to match up for the class, and was hoping for a generic way to do so

Currently it looks like this:

{
  "description": {
    "value": "string",
    "hasValue": true
  }
}

when the actual required JSON is this:

{
  "description": "string"
}

As in the previous question, I'm new to the libraries involved and Googling hasn't helped, so help with the Swagger defaults is muchly appreciated.

Xsjado
  • 347
  • 1
  • 10
  • To add to this, I'm pretty sure I can solve this now with a custom swagger doc for each project, but that's a lot of boilerplate code for what's effectively a debugging tool. I'm simply looking for something along the lines of an annotation that tells swagger what the default value should look like when this class appears. – Xsjado Jun 20 '17 at 03:55

1 Answers1

0

So I figured this out on my own - thought I'd post the answer in case someone else can use it later.

This class creates an action that filters the documentation, copying the values from the inner type directly to the outer type

/// <summary>
/// Sets up the swagger documentation for the optional property
/// </summary>
public static class SwaggerOptionalPropertyFilter
{
    /// <summary>
    /// Get the action that applies the swagger documentation for the optional property
    /// </summary>
    public static Action<SwaggerDocument, HttpRequest> GetFilter()
    {
        return (document, request) =>
        {
            foreach (var kvp in document.Definitions)
            {
                if (!kvp.Key.Contains("OptionalProperty")) continue;

                var val = kvp.Value.Properties.Values.FirstOrDefault();

                if (val == null) continue;

                foreach (var pi in typeof(Schema).GetProperties())
                    pi.SetValue(kvp.Value, pi.GetValue(val, null), null);
            }
        };
    }
}

Then applying it is as simple as changing:

app.UseSwagger();

To:

app.UseSwagger(c => { c.PreSerializeFilters.Add(SwaggerOptionalPropertyFilter.GetFilter()); });
Xsjado
  • 347
  • 1
  • 10