Skip to content

Instantly share code, notes, and snippets.

@GeorgDangl
Last active September 30, 2019 23:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GeorgDangl/af167dd657b8f8b2879f8208341304a4 to your computer and use it in GitHub Desktop.
Save GeorgDangl/af167dd657b8f8b2879f8208341304a4 to your computer and use it in GitHub Desktop.
Fixing NSwag issue with duplicated enum values in the generated Swagger document, https://blog.dangl.me/archive/remove-duplicate-enum-entries-in-swagger-documents-with-nswag-in-aspnet-core/
public enum HttpStatusCode
{
/* Excerpt from System.Net.HttpStatusCode */
RedirectKeepVerb = 307,
TemporaryRedirect = 307
}
services.AddSwaggerDocument(c =>
{
c.PostProcess = (x) =>
{
// Some enum classes use multiple integer values for the same value, e.g.
// System.Net.HttpStatusCode uses these:
// RedirectKeepVerb = 307
// TemporaryRedirect = 307
// MVC is configured to use the StringEnumConverter, and NJsonSchema errorenously
// outputs the duplicates. For the example above, the value 'TemporaryRedirect' is
// serialized twice, 'RedirectKeepVerb' is missing.
// The following post process action should remove duplicated enums
// See https://github.com/RSuter/NJsonSchema/issues/800 for more information
foreach (var enumType in x.Definitions.Select(d => d.Value).Where(d => d.IsEnumeration))
{
var distinctValues = enumType.Enumeration.Distinct().ToList();
enumType.Enumeration.Clear();
foreach (var distinctValue in distinctValues)
{
enumType.Enumeration.Add(distinctValue);
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment