dengjunjie
2025-03-12 f43b7df8400f4fcffc9f19dca0888d61e2b33d5f
ÏîÄ¿´úÂë/WMS/WIDESEA_WMSServer/WIDESEA_Core/Extensions/SwaggerSetup.cs
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,132 @@

using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.Helper;
using static WIDESEA_Core.Extensions.CustomApiVersion;
using Swashbuckle.AspNetCore.Filters;
namespace WIDESEA_Core.Extensions
{
    /// <summary>
    /// Swagger
    /// </summary>
    public static class SwaggerSetup
    {
        /// <summary>
        /// Swagger
        /// </summary>
        /// <param name="services"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddSwaggerSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            var basePath = AppDomain.CurrentDomain.BaseDirectory;
            //var basePath2 = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
            var ApiName = AppSettings.app(new string[] { "ApiName" });
            services.AddSwaggerGen(c =>
            {
                //遍历出全部的版本,做文档信息展示
                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    c.SwaggerDoc(version, new OpenApiInfo
                    {
                        Version = version,
                        Title = $"{ApiName} æŽ¥å£æ–‡æ¡£â€”—{RuntimeInformation.FrameworkDescription}",
                        Description = $"{ApiName} HTTP API " + version,
                        //Contact = new OpenApiContact { Name = ApiName, Email = "Blog.Core@xxx.com", Url = new Uri("https://neters.club") },
                        //License = new OpenApiLicense { Name = ApiName + " å®˜æ–¹æ–‡æ¡£", Url = new Uri("http://apk.neters.club/.doc/") }
                    });
                    //c.OrderActionsBy(o => o.RelativePath);
                });
                c.UseInlineDefinitionsForEnums();
                try
                {
                    var xmlPath = Path.Combine(basePath, "WIDESEA_WMSServer.xml");
                    //默认的第二个参数是false,这个是controller的注释,记得修改
                    c.IncludeXmlComments(xmlPath, true);
                    var xmlModelPath = Path.Combine(basePath, "WIDESEA_Model.xml");
                    c.IncludeXmlComments(xmlModelPath);
                    var xmlDTOPath = Path.Combine(basePath, "WIDESEA_DTO.xml");
                    c.IncludeXmlComments(xmlDTOPath);
                }
                catch (Exception ex)
                {
                    //log.Error("Blog.Core.xml和Blog.Core.Model.xml ä¸¢å¤±ï¼Œè¯·æ£€æŸ¥å¹¶æ‹·è´ã€‚\n" + ex.Message);
                }
                // å¼€å¯åŠ æƒå°é”
                c.OperationFilter<AddResponseHeadersFilter>();
                c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
                // åœ¨header中添加token,传递到后台
                //c.OperationFilter<SecurityRequirementsOperationFilter>();
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT授权token前面需要加上字段Bearer与一个空格,如Bearer token",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });
            }).AddControllers()
            .ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressConsumesConstraintForFormFileParameters = true;
                options.SuppressInferBindingSourcesForParameters = true;
                options.SuppressModelStateInvalidFilter = true;
                options.SuppressMapClientErrors = true;
                options.ClientErrorMapping[404].Link =
                    "https://*/404";
            });
            //services.AddSwaggerGenNewtonsoftSupport();
        }
    }
    /// <summary>
    /// è‡ªå®šä¹‰ç‰ˆæœ¬
    /// </summary>
    public class CustomApiVersion
    {
        /// <summary>
        /// Api接口版本 è‡ªå®šä¹‰
        /// </summary>
        public enum ApiVersions
        {
            /// <summary>
            /// V1 ç‰ˆæœ¬
            /// </summary>
            V1 = 1,
            /// <summary>
            /// V2 ç‰ˆæœ¬
            /// </summary>
            V2 = 2,
        }
    }
}