SwaggerModule.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System.Reflection;
  2. namespace WebTemplate.ServerAspects.Swagger;
  3. public class SwaggerModule : IAppConfigurationModule
  4. {
  5. public void ConfigureServices(IServiceCollection services, IConfigurationRoot config)
  6. {
  7. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  8. services.AddEndpointsApiExplorer();
  9. services.AddSwaggerGen(swaggerGen =>
  10. {
  11. swaggerGen.SupportNonNullableReferenceTypes();
  12. swaggerGen.EnableAnnotations();
  13. // The StringEnumSchemaFilter changes the representation of enums from numbers to strings in
  14. // the OpenApi document. This assumes that the JSON serializer has ben configured to use the
  15. // JsonStringEnumConverter - the two play hand-in-hand.
  16. swaggerGen.SchemaFilter<StringEnumSchemaFilter>();
  17. // This requires the <GenerateDocumentationFile> property to be set to true in the
  18. // .csrpoj file
  19. var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
  20. var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFilename);
  21. if (File.Exists(xmlPath))
  22. {
  23. swaggerGen.IncludeXmlComments(xmlPath);
  24. }
  25. });
  26. }
  27. public void ConfigureApplication(WebApplication app)
  28. {
  29. // OpenApi documents and the Swagger UI should generally not be exposed in production environments based
  30. // on the assumption that production environments are _publicly_ accessible. That is not always the case
  31. // and for somewhat protected scenarios, exposing the API documentation can be very helpful which is why
  32. // we are not using the default "IsDevelopment" check, but instead provide an environment variable that
  33. // can be used to disable Swagger when necessary. Undocumented APIs are just not that useful.
  34. //if (app.Environment.IsDevelopment())
  35. if (Environment.GetEnvironmentVariable("SVC_DISALBE_SWAGGER") != "1")
  36. {
  37. app.UseSwagger();
  38. app.UseSwaggerUI();
  39. }
  40. }
  41. }