.Net Core 添加 Swagger 支持

1. NuGet  中添加 Swashbuckle.AspNetCore

2.添加 Startup 信息

将 Swagger 生成器添加到 Startup.ConfigureServices 方法中的服务集合中:

//注册Swagger生成器,定义一个和多个Swagger 文档
services.AddSwaggerGen(c =>
{
     c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); });

在 Startup.Configure 方法中,启用中间件为生成的 JSON 文档和 Swagger UI 提供服务:

//启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();
//启用中间件服务对swagger-ui,指定Swagger JSON终结点
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); });

3.调试默认页

4.xml 注释信息  1591 忽略注释警告,xml 在bin 目录下,xml名与项目名相同。

 

5.添加特定参数,(query header body path formData)各个 报文都可以配, 功能强大。

 新建 class  实现 配置类 IOperationFilter

    public class SwaggerHeaderOperation : IOperationFilter
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null) operation.Parameters = new List<IParameter>();
            var attrs = context.ApiDescription.ActionDescriptor.AttributeRouteInfo;

            //先判断是否是匿名访问,
            var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
            if (descriptor != null)
            {
                var actionAttributes = descriptor.MethodInfo.GetCustomAttributes(inherit: true);
                bool isAnonymous = actionAttributes.Any(a => a is AllowAnonymousAttribute);
                //非匿名的方法,链接中添加accesstoken值
                if (!isAnonymous)
                {
                    operation.Parameters.Add(new NonBodyParameter()
                    {
                        Name = "accesstoken",
                        In = "header",//query header body path formData
                        Type = "string",
                        Required = false //是否必选
                    });
                }
            }
        }
 
    }

  在 中添加   IServiceCollection.OperationFilter<SwaggerHeaderOperation>();

Startup 最终配置:

        public void ConfigureServices(IServiceCollection services)
        {
           
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //全局配置Json序列化处理
            services.AddMvc()
                .AddJsonOptions(options =>
                {
                    //忽略循环引用
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    //不使用驼峰样式的key
                    //options.SerializerSettings.ContractResolver = new LowercaseContractResolver();
                    //设置时间格式
                    options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
                }
           );

            services.AddSwaggerGen(c =>
            { // 为 Swagger JSON and UI设置xml文档注释路径
                var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
                var xmlPath = Path.Combine(basePath, "AsnycCoreAPI.xml");
                c.IncludeXmlComments(xmlPath);
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
                c.OperationFilter<SwaggerHeaderOperation>();
            });



        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseMvc();


            //启用中间件服务生成Swagger作为JSON终结点
            app.UseSwagger();
            //启用中间件服务对swagger-ui,指定Swagger JSON终结点
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

        }

最后祝大家 国庆节愉快。

猜你喜欢

转载自www.cnblogs.com/j2ee-web-01/p/11599635.html