Skip to content

Instantly share code, notes, and snippets.

@danielcrenna
Last active June 2, 2017 17:15
Show Gist options
  • Save danielcrenna/117d779a4bf00e5815da026a6ba562ba to your computer and use it in GitHub Desktop.
Save danielcrenna/117d779a4bf00e5815da026a6ba562ba to your computer and use it in GitHub Desktop.
Swagger support in .NET Core + Azure
  • Ensure Output/XML is enabled via Properties > Build > Output > Xml documentation file
  • For sanity you may want to suppress the missing XML document warning via Properties > Build > Errors and warnings > Suppress warnings by entering 1591 in the pragma list

You will need these packages for the core feature in addition to ASP.NET Core Configuration packages: Swashbuckle.AspNetCore.SwaggerGen, Swashbuckle.AspNetCore.SwaggerUI

using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.AspNetCore.Swagger;
namespace SwaggerFeature
{
public static class Add
{
/// <summary>
/// See: https://github.com/domaindrivendev/Swashbuckle.AspNetCore
/// Read: https://damienbod.com/2015/12/13/asp-net-5-mvc-6-api-documentation-using-swagger/
///
/// Issue with XML files not showing up in Azure publish:
/// https://github.com/dotnet/sdk/issues/795
/// https://github.com/spboyer/copydocfile-example
/// </summary>
public static IServiceCollection AddSwaggerFeature(this IServiceCollection services, IConfiguration config, IHostingEnvironment env)
{
var settings = config.BindTo<SwaggerSettings>();
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info
{
Version = settings.Version ?? "v1",
Title = settings.Title ?? "MyApi",
Description = settings.Description ?? "This is a description.",
TermsOfService = settings.TermsOfService ?? "http://tos"
});
options.IncludeXmlComments(GetXmlCommentsPath());
options.DescribeAllEnumsAsStrings();
});
return services;
}
private static string GetXmlCommentsPath()
{
return Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, $"{PlatformServices.Default.Application.ApplicationName}.xml");
}
}
}
namespace SwaggerFeature
{
public class SwaggerSettings
{
public string Version { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string TermsOfService { get; set; }
}
}
using Microsoft.AspNetCore.Builder;
namespace SwaggerFeature
{
public static class Use
{
public static IApplicationBuilder UseSwaggerFeature(this IApplicationBuilder app)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
return app;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment