[记录].net 中配置Nlog和Swagger

@[TOC].net 中配置Nlog和Swagger

NLog的配置

需要在program.cs文件中做出如下配置

   public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }).ConfigureLogging(logging =>
                {
                	//这里配置Nlog
                    logging.ClearProviders();
                    logging.ConfigureNLog("nlog.config");// SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                })
              .UseNLog();
    }

以上是基于已经有.netcore和Nlog的使用经验。

Swagger

配置StartUp.cs文件

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddMvc(config =>
            {
                config.Filters.Add<LogFilter>();
            });
            services.AddMvcCore();

            //注册Swagger生成器,定义一个和多个Swagger 文档
            services.AddSwaggerGen(option =>
            {
                option.SwaggerDoc(this.GetType().Namespace, new OpenApiInfo
                {
                    Version = GetType().Assembly.GetName().Version.ToString(),
                    Title = this.GetType().Namespace,
                    Description = "API for " + this.GetType().Namespace,
                    Contact = new OpenApiContact() { Name = "Lampard", Email = "646007589@qq.com" }
                });

  #region 这里可以选择配置,配置以后支持验证信息,对需要走验证的接口测试比较方便
                option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description = "请在下方输入验证信息,格式: Bearer token,注意需要有空格,将token换成你的token值",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                });
                option.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    { new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference()
                        {
                            Id = "Bearer",
                            Type = ReferenceType.SecurityScheme
                        }
                    }, Array.Empty<string>() }
                });
#endregion
                // include document file
                option.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, this.GetType().Namespace + ".xml"), true);
            });
        }
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param> 
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseHttpsRedirection();
            app.UseDefaultFiles();
            app.UseStaticFiles();
            
            //Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
            //Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint
            app.UseSwaggerUI(option =>
            {
                option.SwaggerEndpoint("/swagger/" + this.GetType().Namespace + "/swagger.json", "Version " + GetType().Assembly.GetName().Version.ToString());

            });
        }

SwaggerDoc 方法的第一个参数 对应下面代码中SwaggerEndpoint的json路径,所以要确保这里一致

  app.UseSwaggerUI(option =>
            {
                option.SwaggerEndpoint("/swagger/" + this.GetType().Namespace + "/swagger.json", "Version " + GetType().Assembly.GetName().Version.ToString());

            });

根据上面的内容就想到了一个分组的功能,
用法如下

定义分组文档

 builder.Services.AddSwaggerGen(opt =>
            {

                opt.SwaggerDoc("api-doc", new Microsoft.OpenApi.Models.OpenApiInfo()
                {
                    Version = "v1.0.0",
                    Description = "联合用药接口文档,在测试之前请先拿到Token登陆后再行测试!",
                    Title = "联合用药接口文档",
                    Contact = new Microsoft.OpenApi.Models.OpenApiContact() { Name = "iml6yu", Url = new Uri("http://localhost"), Email = "606007589@qq.com" },
                    TermsOfService = new Uri("http://localhost"),
                    License = new Microsoft.OpenApi.Models.OpenApiLicense()
                    {
                        Name = "No license"
                    }
                });

                opt.SwaggerDoc("test", new Microsoft.OpenApi.Models.OpenApiInfo()
                {
                    Version = "v1.0.0",
                    Description = "测试接口文档!",
                    Title = "测试接口文档",
                    Contact = new Microsoft.OpenApi.Models.OpenApiContact() { Name = "iml6yu", Url = new Uri("http://localhost"), Email = "606007589@qq.com" },
                    TermsOfService = new Uri("http://localhost"),
                    License = new Microsoft.OpenApi.Models.OpenApiLicense()
                    {
                        Name = "No license"
                    }
                });

                // using System.Reflection;
                var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                opt.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename), true);
            });

定义分组文档的Endpoint

 app.UseSwaggerUI(opt =>
                {
                    opt.SwaggerEndpoint("/swagger/api-doc/swagger.json", "默认接口文档");
                    opt.SwaggerEndpoint("/swagger/test/swagger.json", "测试接口文档");
                });

接口上定义分组信息

 /// <summary>
    /// 一个测试数据的控制器
    /// </summary>
    [ApiExplorerSettings(GroupName = "test")]
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {

效果
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值