Swashbuckle.AspNetCore: `SwaggerUIMiddleware` is broken when used with .NET Native AOT

A .NET 7 app can be published as a native executable by setting <PublishAot>true</PublishAot> in the csproj.

I noticed in my test app that the Swagger UI middleware is broken when native AOT is enabled.

The problem is here: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/eede4717ebd80d3e31bd06a6cb47b6b387b18500/src/Swashbuckle.AspNetCore.SwaggerUI/SwaggerUIMiddleware.cs#L121-L131

JsonSerializer.Serialize internally attempts to generate dynamic code which isn’t compatible with native AOT. It throws an error, and a 500 response is returned to the browser.

A fix could be to update these serializer calls to use System.Text.Json source gen - https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-source-generator/. There are other serializer usages in Swashbuckle that you should test out.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 11
  • Comments: 17

Commits related to this issue

Most upvoted comments

Please just add the code generated serializers for the net8 publication of the package to make sure it is trimming and AOT compatible.

Any updates on this topic? .NET 8 releases next week and we would love to use swagger UI.

@quality-leftovers And how do you handle the Swagger UI? Currently the exception happens in the RespondWithIndexHtml method, so I don’t see how using the CLI to generate the spec fixes this issue

Any updates on this topic? .NET 8 releases next week and we would love to use swagger UI.

Still, we don’t have it, is there any update?