Swagger入门
对于新手来说,Swagger入门是十分容易的
1.首先添加nuget包,Swashbuckle.AspNetCore这一个就可以了
2.添加SwaggerConfig文件
/// <summary>
/// SwaggerConfig
/// </summary>
public class SwaggerConfig
{
/// <summary>
///
/// </summary>
/// <param name="services"></param>
public static void Register(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApi", Version = "v1" });
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
c.IncludeXmlComments(Path.Combine(basePath, "Models.xml"));
c.IncludeXmlComments(Path.Combine(basePath, "WebApi.xml"));
c.DocumentFilter<DocF>();
#region JwT Beare认证
c.AddSecurityDefinition("WebApi", new OpenApiSecurityScheme()
{
Description = "请输入Token",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference()
{
Id = "WebApi",
Type = ReferenceType.SecurityScheme
}
}, Array.Empty<string>() }
});
#endregion
});
}
/// <summary>
///
/// </summary>
public static void Config(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger();
//启用中间件服务对swagger-ui,指定Swagger JSON终结点
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("v1/swagger.json", "WebApi");
c.RoutePrefix = "swagger";
c.DocExpansion(DocExpansion.None);
});
}
}
public class DocF : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
swaggerDoc.Tags = new List<OpenApiTag>()
{
new OpenApiTag()
{
Name = "Login",
Description = "登录模块"
}
};
}
}
我的swaggerconfig 添加了jwt的token不需要的可以删除红色部分
3.在statup文件配置swagger
public void ConfigureServices(IServiceCollection services) { services.AddCors();//跨域 services.AddControllers(options => { options.UseCentralRoutePrefix(new RouteAttribute("api/[controller]")); }); SwaggerConfig.Register(services);//添加swagger } public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } //跨域 app.UseCors(options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()); SwaggerConfig.Config(app, env);//添加swagger app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); ////认证 app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
4.如果不想在每个接口前加路由信息的话,做一个统一路由的配置中间件
/// <summary> /// 路由配置信息 /// </summary> public class CentralRouteMiddleware : IApplicationModelConvention { ///<summary> /// 定义一个路由前缀变量 /// </summary> private readonly AttributeRouteModel _centralPrefix; /// <summary> /// 调用时传入指定的路由前缀 /// </summary> /// <param name="routeTemplateProvider"></param> public CentralRouteMiddleware(IRouteTemplateProvider routeTemplateProvider) { _centralPrefix = new AttributeRouteModel(routeTemplateProvider); } public void Apply(ApplicationModel application) { //遍历所有的 Controller foreach (var controller in application.Controllers) { var matchedSelectors = controller.Selectors.Where(x => x.AttributeRouteModel != null).ToList(); if (matchedSelectors.Any()) { foreach (var selectorModel in matchedSelectors) { selectorModel.AttributeRouteModel = new AttributeRouteModel(); } } foreach (var item in controller.Actions) { foreach (var selectorModel in item.Selectors) { if (selectorModel.AttributeRouteModel != null) { selectorModel.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(_centralPrefix, selectorModel.AttributeRouteModel); } else { selectorModel.AttributeRouteModel = new AttributeRouteModel(new RouteAttribute("api/[controller]/[action]")); } } } } } } /// <summary> /// mvc 扩展类 /// </summary> public static class MvcOptionsExtensions { /// <summary> /// 扩展方法 /// </summary> /// <param name="opts"></param> /// <param name="routeAttribute"></param> public static void UseCentralRoutePrefix(this MvcOptions opts, IRouteTemplateProvider routeAttribute) { opts.Conventions.Insert(0, new CentralRouteMiddleware(routeAttribute)); } } }
5.地址栏输入http:localhost:5001/swagger就可以啦