.net core webapi 文档生成

1.NuGet获取Swashbuckle.AspNetCore

2.在Startup.cs的ConfigureServices方法添加如下:

services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Version = "v1",
                    Title = " 订单管理文档"
                });

                options.CustomSchemaIds(CustomSchemaIdSelector);
                // 设置SWAGER JSON和UI的注释路径。
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                options.IncludeXmlComments(xmlPath);
            });
            

在Configure方法中添加如下:

 

 //允许中间件为JSON端点服务生成的Siggg
            app.UseSwagger();
            //使中间件能够服务于轻量级用户界面(HTML、JS、CSS等),并指定SWAGJER JSON端点
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Order API V1");
                // 要在应用程序的根处提供Swagger UI ,请将该RoutePrefix属性设置为空字符串
                c.RoutePrefix = string.Empty;
            });

若出现SchemaId重复问题添加如下:

string CustomSchemaIdSelector(Type modelType)
        {
            if (!modelType.IsConstructedGenericType) return modelType.FullName.Replace("[]", "Array");

            var prefix = modelType.GetGenericArguments()
                .Select(genericArg => CustomSchemaIdSelector(genericArg))
                .Aggregate((previous, current) => previous + current);

            return prefix + modelType.FullName.Split('`').First();
        }

 

posted on 2022-07-05 16:10  power_yu  阅读(112)  评论(0编辑  收藏  举报

导航