The second package using Swashbuckle.AspNetCore3.0

About Swashbuckle.AspNetCore3.0

A built using the API ASP.NET Core of Swagger tool. Generate pretty API documentation directly from your routes, controllers and models, including UI used to explore and test operation.
Project Home: https://github.com/domaindrivendev/Swashbuckle.AspNetCore
official sample project: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/tree/master/test/WebSites

I wrote before use Swashbuckle.AspNetCore-v1.10 is now  Swashbuckle.AspNetCore been upgraded to 3.0, just open a new pit (blog reconstruction) to re-package the next, will draw all things to some of the separate class library, as much as possible and avoid coupling project, so that it can be quickly used in other projects.

Run the sample

Packaging Code

Blog be completed and then reconstructed full open source code, the step of self-reference to the following package

1. Create a new class library and add a reference

I quote the following version

    <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.1.1" /> <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.1" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="3.0.0" />

2. Construction of model parameters CustsomSwaggerOptions.cs

    public class CustsomSwaggerOptions
    {
        /// <summary> /// 项目名称 /// </summary> public string ProjectName { get; set; } = "My API"; /// <summary> /// 接口文档显示版本 /// </summary> public string[] ApiVersions { get; set; } /// <summary> /// 接口文档访问路由前缀 /// </summary> public string RoutePrefix { get; set; } = "swagger"; /// <summary> /// 使用自定义首页 /// </summary> public bool UseCustomIndex { get; set; } /// <summary> /// UseSwagger Hook /// </summary> public Action<SwaggerOptions> UseSwaggerAction { get; set; } /// <summary> /// UseSwaggerUI Hook /// </summary> public Action<SwaggerUIOptions> UseSwaggerUIAction { get; set; } /// <summary> /// AddSwaggerGen Hook /// </summary> public Action<SwaggerGenOptions> AddSwaggerGenAction { get; set; } }

3. Version Control default parameter interface SwaggerDefaultValueFilter.cs

    public class SwaggerDefaultValueFilter : IOperationFilter
    {
        public void Apply(Swashbuckle.AspNetCore.Swagger.Operation operation, OperationFilterContext context) { // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/412 // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/413 foreach (var parameter in operation.Parameters.OfType<NonBodyParameter>()) { var description = context.ApiDescription.ParameterDescriptions.FirstOrDefault(p => p.Name == parameter.Name); if (description == null) return; if (parameter.Description == null) { parameter.Description = description.ModelMetadata.Description; } if (description.RouteInfo != null) { parameter.Required |= !description.RouteInfo.IsOptional; if (parameter.Default == null) parameter.Default = description.RouteInfo.DefaultValue; } } }

4. CustomSwaggerServiceCollectionExtensions.cs

    public static class CustomSwaggerServiceCollectionExtensions
    {
        public static IServiceCollection AddCustomSwagger(this IServiceCollection services) { return AddCustomSwagger(services, new CustsomSwaggerOptions()); } public static IServiceCollection AddCustomSwagger(this IServiceCollection services, CustsomSwaggerOptions options) { services.AddSwaggerGen(c => { if (options.ApiVersions == null) return; foreach (var version in options.ApiVersions) { c.SwaggerDoc(version, new Info { Title = options.ProjectName, Version = version }); } c.OperationFilter<SwaggerDefaultValueFilter>(); options.AddSwaggerGenAction?.Invoke(c); }); return services; } }

5. SwaggerBuilderExtensions.cs

    public static class SwaggerBuilderExtensions
    {
        public static IApplicationBuilder UseCustomSwagger(this IApplicationBuilder app) { return UseCustomSwagger(app, new CustsomSwaggerOptions()); } public static IApplicationBuilder UseCustomSwagger(this IApplicationBuilder app, CustsomSwaggerOptions options) { app.UseSwagger(opt => { if (options.UseSwaggerAction == null) return; options.UseSwaggerAction(opt); }); app.UseSwaggerUI(c => { if (options.ApiVersions == null) return; c.RoutePrefix = options.RoutePrefix; c.DocumentTitle = options.ProjectName; if (options.UseCustomIndex) { c.UseCustomSwaggerIndex(); } foreach (var item in options.ApiVersions) { c.SwaggerEndpoint($"/swagger/{item}/swagger.json", $"{item}"); } options.UseSwaggerUIAction?.Invoke(c); }); return app; } /// <summary> /// 使用自定义首页 /// </summary> /// <returns></returns> public static void UseCustomSwaggerIndex(this SwaggerUIOptions c) { var currentAssembly = typeof(CustsomSwaggerOptions).GetTypeInfo().Assembly; c.IndexStream = () => currentAssembly.GetManifestResourceStream($"{currentAssembly.GetName().Name}.index.html"); } }

6. model initialization

    private CustsomSwaggerOptions CURRENT_SWAGGER_OPTIONS = new CustsomSwaggerOptions()
    {
        ProjectName = "墨玄涯博客接口",
        ApiVersions = new string[] { "v1", "v2" },//要显示的版本 UseCustomIndex = true, RoutePrefix = "swagger", AddSwaggerGenAction = c => { var filePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, typeof(Program).GetTypeInfo().Assembly.GetName().Name + ".xml"); c.IncludeXmlComments(filePath, true); }, UseSwaggerAction = c => { }, UseSwaggerUIAction = c => { } };

7. Use the api project

Add a reference to the new library, and enable versioning need to add Nuget package for the project output in webapi project: Microsoft.AspNetCore.Mvc.Versioning, Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer (If you need to add versioning)

I quote the following version

    <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="2.3.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="2.2.0" />

Startup.cs Code

    public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //版本控制 services.AddMvcCore().AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VVV"); services.AddApiVersioning(option => { // allow a client to call you without specifying an api version // since we haven't configured it otherwise, the assumed api version will be 1.0 option.AssumeDefaultVersionWhenUnspecified = true; option.ReportApiVersions = false; }); //custom swagger services.AddCustomSwagger(CURRENT_SWAGGER_OPTIONS); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //custom swagger //自动检测存在的版本 // CURRENT_SWAGGER_OPTIONS.ApiVersions = provider.ApiVersionDescriptions.Select(s => s.GroupName).ToArray(); app.UseCustomSwagger(CURRENT_SWAGGER_OPTIONS); app.UseMvc(); }

The key code for dismantling

xml annotation method of action

new CustsomSwaggerOptions(){
    AddSwaggerGenAction = c =>
    {
        var filePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, typeof(Program).GetTypeInfo().Assembly.GetName().Name + ".xml");
        //controller及action注释 c.IncludeXmlComments(filePath, true); } }

Of course, also need to generate xml, editing solution added (or project properties in vs in -> Generate -> tick generates xml document file) follows segment

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <DocumentationFile>.\项目名称.xml</DocumentationFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>.\项目名称.xml</DocumentationFile> </PropertyGroup>

Currently .net core2.1 me to this project will generate xml directory, it may be necessary to add it in .gitignore.

version control

Add Nuget package: Microsoft.AspNetCore.Mvc.Versioning, Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer
and provided in ConfigureServices

    //版本控制
    services.AddMvcCore().AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VVV");
    services.AddApiVersioning(option =>
    {
        // allow a client to call you without specifying an api version
        // since we haven't configured it otherwise, the assumed api version will be 1.0
        option.AssumeDefaultVersionWhenUnspecified = true; option.ReportApiVersions = false; });

Use controller

    /// <summary>
    /// 测试接口 /// </summary> [ApiVersion("1.0")] [Route("api/v{api-version:apiVersion}/test")] [ApiController] public class TestController : ControllerBase { }

Custom Theme

The index.html amended as embedded resources can be used GetManifestResourceStreamto obtain the file stream, use this html, you can use your own var configObject = JSON.parse('%(ConfigObject)');get configuration information swagger, so based on this information to write your own theme can be.

    /// <summary>
    /// 使用自定义首页 /// </summary> /// <returns></returns> public static void UseCustomSwaggerIndex(this SwaggerUIOptions c) { var currentAssembly = typeof(CustsomSwaggerOptions).GetTypeInfo().Assembly; c.IndexStream = () => currentAssembly.GetManifestResourceStream($"{currentAssembly.GetName().Name}.index.html"); }

Methods To inject css, js then call the corresponding interface in UseSwaggerUIAction delegate, official documents

In addition, the current swagger-ui 3.19.0 does not support multi-language, but you can use js to modify some of the things needed
such as this to modify the header information in the onload event index.html

document.getElementsByTagName(
  'span'
)[0].innerText = document
  .getElementsByTagName('span')[0] .innerText.replace('swagger', '项目接口文档') document.getElementsByTagName( 'span' )[1].innerText = document .getElementsByTagName('span')[1] .innerText.replace('Select a spec', '版本选择')

When used tracked Swashbuckle.AspNetCore3.0 theme when looking at the finished solution swagger-ui to 3.19.0 , from issues2488 learned does not currently support multiple languages, other problems you can also view this warehouse
encountered in the course of problems, and issues readme basically has the answer, you can read a lot of problems encountered

Reference article

Author: Yi ink 
individual station: http://www.yimo.link 
purely static tools site: http://tools.yimo.link/ 
Description: Welcome Paizhuan, the deficiency also pointed out Wangyuandongli faithful; 
confused about It is because too many want to do too little.

 
Category:  the .NET Core
Tags:  the .NET Core Swagger

 

 

About Swashbuckle.AspNetCore3.0

A built using the API ASP.NET Core of Swagger tool. Generate pretty API documentation directly from your routes, controllers and models, including UI used to explore and test operation.
Project Home: https://github.com/domaindrivendev/Swashbuckle.AspNetCore
official sample project: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/tree/master/test/WebSites

I wrote before use Swashbuckle.AspNetCore-v1.10 is now  Swashbuckle.AspNetCore been upgraded to 3.0, just open a new pit (blog reconstruction) to re-package the next, will draw all things to some of the separate class library, as much as possible and avoid coupling project, so that it can be quickly used in other projects.

Run the sample

Packaging Code

Blog be completed and then reconstructed full open source code, the step of self-reference to the following package

1. Create a new class library and add a reference

I quote the following version

    <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.1.1" /> <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.1" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="3.0.0" />

2. Construction of model parameters CustsomSwaggerOptions.cs

    public class CustsomSwaggerOptions
    {
        /// <summary> /// 项目名称 /// </summary> public string ProjectName { get; set; } = "My API"; /// <summary> /// 接口文档显示版本 /// </summary> public string[] ApiVersions { get; set; } /// <summary> /// 接口文档访问路由前缀 /// </summary> public string RoutePrefix { get; set; } = "swagger"; /// <summary> /// 使用自定义首页 /// </summary> public bool UseCustomIndex { get; set; } /// <summary> /// UseSwagger Hook /// </summary> public Action<SwaggerOptions> UseSwaggerAction { get; set; } /// <summary> /// UseSwaggerUI Hook /// </summary> public Action<SwaggerUIOptions> UseSwaggerUIAction { get; set; } /// <summary> /// AddSwaggerGen Hook /// </summary> public Action<SwaggerGenOptions> AddSwaggerGenAction { get; set; } }

3. Version Control default parameter interface SwaggerDefaultValueFilter.cs

    public class SwaggerDefaultValueFilter : IOperationFilter
    {
        public void Apply(Swashbuckle.AspNetCore.Swagger.Operation operation, OperationFilterContext context) { // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/412 // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/413 foreach (var parameter in operation.Parameters.OfType<NonBodyParameter>()) { var description = context.ApiDescription.ParameterDescriptions.FirstOrDefault(p => p.Name == parameter.Name); if (description == null) return; if (parameter.Description == null) { parameter.Description = description.ModelMetadata.Description; } if (description.RouteInfo != null) { parameter.Required |= !description.RouteInfo.IsOptional; if (parameter.Default == null) parameter.Default = description.RouteInfo.DefaultValue; } } }

4. CustomSwaggerServiceCollectionExtensions.cs

    public static class CustomSwaggerServiceCollectionExtensions
    {
        public static IServiceCollection AddCustomSwagger(this IServiceCollection services) { return AddCustomSwagger(services, new CustsomSwaggerOptions()); } public static IServiceCollection AddCustomSwagger(this IServiceCollection services, CustsomSwaggerOptions options) { services.AddSwaggerGen(c => { if (options.ApiVersions == null) return; foreach (var version in options.ApiVersions) { c.SwaggerDoc(version, new Info { Title = options.ProjectName, Version = version }); } c.OperationFilter<SwaggerDefaultValueFilter>(); options.AddSwaggerGenAction?.Invoke(c); }); return services; } }

5. SwaggerBuilderExtensions.cs

    public static class SwaggerBuilderExtensions
    {
        public static IApplicationBuilder UseCustomSwagger(this IApplicationBuilder app) { return UseCustomSwagger(app, new CustsomSwaggerOptions()); } public static IApplicationBuilder UseCustomSwagger(this IApplicationBuilder app, CustsomSwaggerOptions options) { app.UseSwagger(opt => { if (options.UseSwaggerAction == null) return; options.UseSwaggerAction(opt); }); app.UseSwaggerUI(c => { if (options.ApiVersions == null) return; c.RoutePrefix = options.RoutePrefix; c.DocumentTitle = options.ProjectName; if (options.UseCustomIndex) { c.UseCustomSwaggerIndex(); } foreach (var item in options.ApiVersions) { c.SwaggerEndpoint($"/swagger/{item}/swagger.json", $"{item}"); } options.UseSwaggerUIAction?.Invoke(c); }); return app; } /// <summary> /// 使用自定义首页 /// </summary> /// <returns></returns> public static void UseCustomSwaggerIndex(this SwaggerUIOptions c) { var currentAssembly = typeof(CustsomSwaggerOptions).GetTypeInfo().Assembly; c.IndexStream = () => currentAssembly.GetManifestResourceStream($"{currentAssembly.GetName().Name}.index.html"); } }

6. model initialization

    private CustsomSwaggerOptions CURRENT_SWAGGER_OPTIONS = new CustsomSwaggerOptions()
    {
        ProjectName = "墨玄涯博客接口",
        ApiVersions = new string[] { "v1", "v2" },//要显示的版本 UseCustomIndex = true, RoutePrefix = "swagger", AddSwaggerGenAction = c => { var filePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, typeof(Program).GetTypeInfo().Assembly.GetName().Name + ".xml"); c.IncludeXmlComments(filePath, true); }, UseSwaggerAction = c => { }, UseSwaggerUIAction = c => { } };

7. Use the api project

Add a reference to the new library, and enable versioning need to add Nuget package for the project output in webapi project: Microsoft.AspNetCore.Mvc.Versioning, Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer (If you need to add versioning)

I quote the following version

    <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="2.3.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="2.2.0" />

Startup.cs Code

    public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //版本控制 services.AddMvcCore().AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VVV"); services.AddApiVersioning(option => { // allow a client to call you without specifying an api version // since we haven't configured it otherwise, the assumed api version will be 1.0 option.AssumeDefaultVersionWhenUnspecified = true; option.ReportApiVersions = false; }); //custom swagger services.AddCustomSwagger(CURRENT_SWAGGER_OPTIONS); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //custom swagger //自动检测存在的版本 // CURRENT_SWAGGER_OPTIONS.ApiVersions = provider.ApiVersionDescriptions.Select(s => s.GroupName).ToArray(); app.UseCustomSwagger(CURRENT_SWAGGER_OPTIONS); app.UseMvc(); }

The key code for dismantling

xml annotation method of action

new CustsomSwaggerOptions(){
    AddSwaggerGenAction = c =>
    {
        var filePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, typeof(Program).GetTypeInfo().Assembly.GetName().Name + ".xml");
        //controller及action注释 c.IncludeXmlComments(filePath, true); } }

Of course, also need to generate xml, editing solution added (or project properties in vs in -> Generate -> tick generates xml document file) follows segment

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <DocumentationFile>.\项目名称.xml</DocumentationFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>.\项目名称.xml</DocumentationFile> </PropertyGroup>

Currently .net core2.1 me to this project will generate xml directory, it may be necessary to add it in .gitignore.

version control

Add Nuget package: Microsoft.AspNetCore.Mvc.Versioning, Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer
and provided in ConfigureServices

    //版本控制
    services.AddMvcCore().AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VVV");
    services.AddApiVersioning(option =>
    {
        // allow a client to call you without specifying an api version
        // since we haven't configured it otherwise, the assumed api version will be 1.0
        option.AssumeDefaultVersionWhenUnspecified = true; option.ReportApiVersions = false; });

Use controller

    /// <summary>
    /// 测试接口 /// </summary> [ApiVersion("1.0")] [Route("api/v{api-version:apiVersion}/test")] [ApiController] public class TestController : ControllerBase { }

Custom Theme

The index.html amended as embedded resources can be used GetManifestResourceStreamto obtain the file stream, use this html, you can use your own var configObject = JSON.parse('%(ConfigObject)');get configuration information swagger, so based on this information to write your own theme can be.

    /// <summary>
    /// 使用自定义首页 /// </summary> /// <returns></returns> public static void UseCustomSwaggerIndex(this SwaggerUIOptions c) { var currentAssembly = typeof(CustsomSwaggerOptions).GetTypeInfo().Assembly; c.IndexStream = () => currentAssembly.GetManifestResourceStream($"{currentAssembly.GetName().Name}.index.html"); }

Methods To inject css, js then call the corresponding interface in UseSwaggerUIAction delegate, official documents

In addition, the current swagger-ui 3.19.0 does not support multi-language, but you can use js to modify some of the things needed
such as this to modify the header information in the onload event index.html

document.getElementsByTagName(
  'span'
)[0].innerText = document
  .getElementsByTagName('span')[0] .innerText.replace('swagger', '项目接口文档') document.getElementsByTagName( 'span' )[1].innerText = document .getElementsByTagName('span')[1] .innerText.replace('Select a spec', '版本选择')

When used tracked Swashbuckle.AspNetCore3.0 theme when looking at the finished solution swagger-ui to 3.19.0 , from issues2488 learned does not currently support multiple languages, other problems you can also view this warehouse
encountered in the course of problems, and issues readme basically has the answer, you can read a lot of problems encountered

Reference article

Guess you like

Origin www.cnblogs.com/webenh/p/11577749.html