本文主要是介绍Swagger配置WebApi,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
- 前言
- 通用必备操作
- 添加Swashbuckle.AspNetCore引用(.net 5项目创建完整版项目时会自动引用)
- 创建版本枚举类
- 添加中间件
- 配置swagger版本管理
- 一.创建版本枚举类
- 二.在ConfigureServices中注册swagger
- 三.添加中间件
- 四.声明组名称及路由
- 五.为公开方法声明访问修饰符及路由
- 配置Token验证按钮
- 一.在ConfigureServices中注册swagger
- 二.添加中间件
- 配置swagger显示注释
- 一.添加xml
- 二.在ConfigureServices中注册swagger
- 配置jwt访问校验(需要了解jwt基础知识)
- 一.添加Microsoft.AspNetCore.Authentication.JwtBearer引用
- 二.在appsettings.json中配置jwt信息
- 三.在ConfigureServices中注册swagger
- 四.添加中间件
- 五.为公开方法添加特性
前言
本篇介绍.net core ,.net 5 通用的swagger配置方式
GetHub源码地址: 点击跳转.
通用必备操作
添加Swashbuckle.AspNetCore引用(.net 5项目创建完整版项目时会自动引用)
创建版本枚举类
namespace SwaggerWebApi.Utilty
{public class CustomApiVersions{public enum ApiVersions{v1 = 1,v2 = 2,v3 = 3,v4 = 4}}
}
添加中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}#region Swagger中间件app.UseSwagger();app.UseSwaggerUI(c =>{typeof(ApiVersions).GetEnumNames().Reverse().ToList().ForEach(version =>{c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{version}");});});// app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwaggerWebApi v1"));#endregionapp.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}
配置swagger版本管理
一.创建版本枚举类
namespace SwaggerWebApi.Utilty
{public class CustomApiVersions{public enum ApiVersions{v1 = 1,v2 = 2,v3 = 3,v4 = 4}}
}
二.在ConfigureServices中注册swagger
services.AddSwaggerGen(c =>{#region 动态注册swagger版本管理typeof(ApiVersions).GetEnumNames().Reverse().ToList().ForEach(version =>{c.SwaggerDoc(version, new OpenApiInfo(){Title = $"{version}:版本标题",Version = version,Description = $"{version}版本的内部主要包含了XXXXX"});});#endregion//c.SwaggerDoc("v1", new OpenApiInfo { Title = "SwaggerWebApi", Version = "v1" });});
三.添加中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}#region Swagger中间件app.UseSwagger();app.UseSwaggerUI(c =>{typeof(ApiVersions).GetEnumNames().Reverse().ToList().ForEach(version =>{c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{version}");});});// app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwaggerWebApi v1"));#endregionapp.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}
四.声明组名称及路由
GroupName = "v1" "v1"名称需要与枚举类对应
[Route("api/[controller]")][ApiExplorerSettings(GroupName = "v1")][ApiController]public class V1Controller : Controller{}
五.为公开方法声明访问修饰符及路由
名称相近的方法必须声明路由 例如:AddNewV1与AddV1
[Route("api/[controller]")][ApiExplorerSettings(GroupName = "v1")][ApiController]public class V1Controller : Controller{[HttpGet][Route("api/[controller]/GetV1")]public string GetV1(){return Newtonsoft.Json.JsonConvert.SerializeObject(new{Title = "Hello World"});}}
配置Token验证按钮
一.在ConfigureServices中注册swagger
#region Swagger//注册swagger服务services.AddSwaggerGen(c =>{#region 添加Token验证按钮 //添加授权c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme{Description = "请输入Token,格式为:Bearer 带有开头的",Name = "Authorization",//jwt默认参数名称In = ParameterLocation.Header,//把jwt存放在header中Type = SecuritySchemeType.ApiKey,BearerFormat = "JWT",Scheme = "Bearer"});//认证方式,此方式为全局添加c.AddSecurityRequirement(new OpenApiSecurityRequirement{{new OpenApiSecurityScheme{Reference=new OpenApiReference{Type=ReferenceType.SecurityScheme,Id="Bearer"}},new string[] { }}});#endregion});#endregion
二.添加中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}#region Swagger中间件app.UseSwagger();app.UseSwaggerUI(c =>{typeof(ApiVersions).GetEnumNames().Reverse().ToList().ForEach(version =>{c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{version}");});});// app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwaggerWebApi v1"));#endregionapp.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}
配置swagger显示注释
一.添加xml
二.在ConfigureServices中注册swagger
## 一.在ConfigureServices中注册swagger
```csharp
#region Swagger//注册swagger服务services.AddSwaggerGen(c =>{//添加中文注释var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);Console.WriteLine("basePath: " + basePath);var commentsFileName = typeof(Program).Assembly.GetName().Name + ".XML";Console.WriteLine("commentsFileName: " + commentsFileName);var xmlPath = Path.Combine(basePath, commentsFileName);c.IncludeXmlComments(xmlPath);});#endregion
配置jwt访问校验(需要了解jwt基础知识)
一.添加Microsoft.AspNetCore.Authentication.JwtBearer引用
二.在appsettings.json中配置jwt信息
{"Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"}},"AllowedHosts": "*","audience": "http://localhost:8082","issuer": "http://localhost:8082","SecurityKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB"
}
三.在ConfigureServices中注册swagger
#region jwt校验
//使用方法详见https://blog.csdn.net/tx1721110240/article/details/110355328
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{options.TokenValidationParameters = new TokenValidationParameters{ValidateIssuer = true,//是否验证IssuerValidateAudience = true,//是否验证AudienceValidateLifetime = true,//是否验证失效时间ValidateIssuerSigningKey = true,//是否验证SecurityKeyValidAudience = this.Configuration["audience"],//AudienceValidIssuer = this.Configuration["issuer"],//Issuer,这两项和前面签发jwt的设置一致IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.Configuration["SecurityKey"])),//拿到SecurityKey//AudienceValidator = (m, n, z) =>//{// return m != null && m.FirstOrDefault().Equals(this.Configuration["audience"]);//},//自定义校验规则,可以新登录后将之前的无效};
});
#endregion
四.添加中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}#region Swagger中间件app.UseSwagger();app.UseSwaggerUI(c =>{typeof(ApiVersions).GetEnumNames().Reverse().ToList().ForEach(version =>{c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{version}");});});// app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwaggerWebApi v1"));#endregion#region jwtapp.UseAuthentication();//注意添加这一句,启用验证#endregionapp.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}
五.为公开方法添加特性
标识[Microsoft.AspNetCore.Authorization.Authorize] 表示 :访问这个特性下的方法需要验证jwt
标识[Microsoft.AspNetCore.Authorization.AllowAnonymous]表示 :访问这个特性下的方法不需要验证jwt
名称相近的方法必须声明路由 例如:AddNewV1与AddV1
[Route("api/[controller]")][ApiExplorerSettings(GroupName = "v1")][ApiController][Microsoft.AspNetCore.Authorization.Authorize]public class V1Controller : Controller{[HttpGet][Route("api/[controller]/GetV1")][Microsoft.AspNetCore.Authorization.AllowAnonymous]public string GetV1(){return Newtonsoft.Json.JsonConvert.SerializeObject(new{Title = "Hello World"});}/// <summary>/// 这里是DeleteV1/// </summary>/// <returns>字符串</returns>[HttpDelete][Route("api/[controller]/DeleteV1")]public string DeleteV1(){return Newtonsoft.Json.JsonConvert.SerializeObject(new{Success = true,Message = "操作成功"});}}
这篇关于Swagger配置WebApi的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!