Skip to content

Instantly share code, notes, and snippets.

@rebelweb
Created February 7, 2020 05:41
Show Gist options
  • Save rebelweb/7fb206db585f19a1113ed5882cde4d5f to your computer and use it in GitHub Desktop.
Save rebelweb/7fb206db585f19a1113ed5882cde4d5f to your computer and use it in GitHub Desktop.
Swashbuckle Helper
using System;
using System.IO;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Builder;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace DayHiker.API.Helpers
{
/// <summary>
/// Swagger Setup Dependency Injection Methods and Helpers
/// </summary>
public static class SwashbuckleHelper
{
/// <summary>
/// Dependency Injection method to use Swagger for APi Documentation
/// </summary>
/// <param name="services">The Dependency Injection Container</param>
/// <returns>The Dependency Injection container with services added</returns>
public static IServiceCollection UseSwashbuckle(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "DayHiker API", Version = "v1" });
c.AddDocumentation();
});
return services;
}
/// <summary>
/// App Setup Extension Method
/// </summary>
/// <param name="builder">The application builder</param>
public static void SetupSwagger(this IApplicationBuilder builder)
{
builder.UseSwagger();
builder.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "DayHiker API");
});
}
/// <summary>
/// Extension method to add documentation files to swagger. This allows comments to visable in the UI
/// </summary>
/// <param name="opts">Swagger options</param>
private static void AddDocumentation(this SwaggerGenOptions opts)
{
foreach(var docFile in DocumentationFiles)
{
string xmlPath = Path.Combine(AppContext.BaseDirectory, docFile);
opts.IncludeXmlComments(xmlPath);
}
}
/// <summary>
/// Gets all the documentation files for the various class library
/// </summary>
/// <returns>An array of documentation filenames</returns>
private static string[] DocumentationFiles => Directory.GetFiles(AppContext.BaseDirectory)
.Where(q => Path.GetExtension(q) == ".xml").ToArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment