ASP.NET Core 使用Swagger生成在线api文档
参考:
基本用法: https://www.cnblogs.com/yilezhu/p/9241261.html
加token授权:https://www.cnblogs.com/shenghuotaiai/p/12551268.html
整合后调通,上代码:
Controller:
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace WebApp1.Controllers { [Route("XxxApi/[controller]")] public class WebApiController : Controller { ////// 获取Token /// /// 明文 /// 密文 [HttpGet, Route("GetToken")] public ActionResult<string> GetToken(string uid) { var claims = new List { new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),//生效时间 new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),//过期时间 new Claim(ClaimTypes.Name, uid) }; // 密钥 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecurityKey123456")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); JwtSecurityToken jwt = new JwtSecurityToken( claims: claims, signingCredentials: creds ); var handler = new JwtSecurityTokenHandler(); // 生成 jwt字符串 var strJWT = handler.WriteToken(jwt); return Ok(strJWT); } /// /// 获取用户姓名 /// /// 用户唯一标识id /// 用户姓名 [HttpGet, Authorize, Route("GetUserName")] public string GetUserName(int id) { return "abc"; } } }
Startup:
using db_face.Models; using db_oa.Models; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using System; using System.IO; using System.Text; namespace WebApp1 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //asp.net 使用 Authentication services.AddAuthentication(s => { s.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; s.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; s.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false,//是否验证Issuer ValidateAudience = false,//是否验证Audience ValidateLifetime = true,//是否验证失效时间 ClockSkew = TimeSpan.FromMinutes(1), ValidateIssuerSigningKey = true,//是否验证SecurityKey IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecurityKey123456")) }; }); services.AddControllersWithViews(); //注册Swagger生成器,定义一个和多个Swagger 文档 services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "用户信息 API", Description = "这是一个查询用户信息的 Web API", Contact = new OpenApiContact { Name = "张三", Email = "abc@abc.com" } }); // 为 Swagger JSON and UI设置xml文档注释路径 var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location); var xmlPath = Path.Combine(basePath, "WebApp1.xml"); c.IncludeXmlComments(xmlPath); //为 Swagger UI 页面顶部 加上 按钮及填写token的弹框 c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "授权(数据将在请求头中进行传递)直接在下面框中输入Bearer {token}(注意两者之间是一个空格) \"", Name = "Authorization",//jwt默认的参数名称 In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中) Type = SecuritySchemeType.ApiKey }); //为 Swagger UI 页面上列出的每个方法加 小锁图标(每个请求都会在head加token) c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "Bearer", Type = ReferenceType.SecurityScheme } }, Array.Empty<string>() } }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); //启用中间件服务生成Swagger作为JSON终结点 app.UseSwagger(); //启用中间件服务对swagger-ui,指定Swagger JSON终结点 app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1"); //c.RoutePrefix = string.Empty; }); } } }
对于不熟的人来说还是会遇到一些坑的:
SecurityKey长度必须16位以上,不然运行时会报错。
swagger页面上 调页面的api发的请求中head中缺少token信息,报401,services.AddSwaggerGen中需要AddSecurityRequirement详见上述代码。
一直在配合框架写它需要的代码,不喜欢。