[记录].net core 3.0 中配置Nlog和Swagger
@[TOC].net core3.0 中配置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());
});
}