Remove Duplicate Enum Entries in Swagger Documents with NSwag in ASP.NET Core

Georg Dangl by Georg Dangl in DotNet Thursday, January 03, 2019

Thursday, January 03, 2019

Posted in Asp.Net Core

NSwag and NJsonSchema are great tools that make it super easy to integrate Swagger / OpenAPI specification documents in your ASP.NET Core apps.

Basically, you simply define your web server backend and then all your API endpoints and models are automatically available for anyone to generate clients in their favorite language.

In such scenarios, NSwag is often configured to use a StringEnumConverter, meaning that enum values are meant to be serialized as strings when they're sent over the wire. However, there's one nasty thing that's allowed by the C# specification when it comes to this:

You might actually have two different string representations that both match an internally used integer identifier. That becomes a problem when you're using string serialization for enumerations but track them internally by their integer id.

In NJsonSchema, for example, there's a small bug that would lead to TemporaryRedirect being serialized twice in this case. That's sometimes not a problem, but strongly typed languages like C# or Java will fail to compile the generated client code.

To solve this, you can simply remove these distinct values in a PostProcess action when you're setting up NSwag for your ASP.NET Core application:

Happy serializing!

Share this post

comments powered by Disqus

About me

Hi, my name's George! I love coding and blogging about it. I focus on all things around .Net, Web Development and DevOps.


Need a consultant for BIM, GAEB or Software Development?

Contact me at [email protected], +49 (173) 56 45 689 or visit my professional page!

// Just 💗 Coding

Social Links