码迷,mamicode.com
首页 > Web开发 > 详细

.Net Core 添加 Swagger 支持

时间:2019-09-27 19:27:46      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:agg   formdata   ==   rip   resolve   config   sre   keyword   body   

 

 

 

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");
            });

        }

 

 

最后祝大家 国庆节愉快。

 

.Net Core 添加 Swagger 支持

标签:agg   formdata   ==   rip   resolve   config   sre   keyword   body   

原文地址:https://www.cnblogs.com/j2ee-web-01/p/11599635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!