先亮源代码: https://github.com/axzxs2001/Asp.NetCoreExperiment/tree/master/Asp.NetCoreExperiment/SwaggerDemo
这篇博文不是对 asp.net core 中使用 Swagger 作介绍, 因为社区博客作了详细说明.
今天主要说一下 Swagger 在 Ocelot 网关权限验证模式下的访问, 以及 Swagger 请求应答的数据格式.
首先创建四个项目:
SwaggerOcelot:asp.net core web api 类型, api 网关项目
SwaggerAuthorize:asp.net core web api 类型, 用户验证项目
SwaggerAPI01:asp.net core web api 类型, api 1 项目
SWaggerAPI02:asp.net core web api 类型, api 2 项目
首先在四个项目中添加基于 Jwt 的 Toekn 认证, 参见 https://www.cnblogs.com/axzxs2001/p/9250588.html
再在四个项目 Nuget 中引入 Swashbuckle.AspNetCore, 我的 Demo 中用的是 2.5.0, 再分别配置 Swagger
SwaggerAuthorize Starup.cs 配置
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddTokenJwtAuthorize();
- services.AddMvc()
- .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
- services.AddSwaggerGen(options =>
- {
- options.SwaggerDoc("SwaggerAuthorize", new Info { Title = "Authorize", Version = "v1", Contact = new Contact { Email = "285130205@qq.com", Name = "Authorize", Url = "http://0.0.0.0" }, Description = "Authorize 项目" });
- var basePath = PlatformServices.Default.Application.ApplicationBasePath;
- var xmlPath = Path.Combine(basePath, "SwaggerAuthorize.xml");
- options.IncludeXmlComments(xmlPath);
- });
- }
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- app.UseMvc()
- .UseSwagger(options =>
- {
- options.RouteTemplate = "{documentName}/swagger.json";
- })
- .UseSwaggerUI(options =>
- {
- options.SwaggerEndpoint("/SwaggerAuthorize/swagger.json", "Authorize");
- });
- }
SwaggerAPI01,SwaggerAPI02 类似, Starup.cs 配置, 其中让 Swagger 支付 Token 验证, 就是要在这部分添加 Swagger 配置
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddApiJwtAuthorize((context) =>
- {
- return true;
- });
- services.AddSwaggerGen(options =>
- {
- options.SwaggerDoc("SwaggerAPI01", new Info { Title = "API01", Version = "v1", Contact = new Contact { Email = "285130205@qq.com", Name = "API01", Url = "http://0.0.0.0" }, Description = "API01 项目" });
- var basePath = PlatformServices.Default.Application.ApplicationBasePath;
- var xmlPath = Path.Combine(basePath, "SwaggerAPI01.xml");
- options.IncludeXmlComments(xmlPath);
- // 这里是给 Swagger 添加验证的部分
- options.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description = "请输入带有 Bearer 的 Token", Name = "Authorization", Type = "apiKey" });
- options.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
- {
- "Bearer",
- Enumerable.Empty<string>()
- }
- });
- });
- services
- .AddMvc()
- .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
- }
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- app.UseMvc()
- .UseSwagger(options =>
- {
- options.RouteTemplate = "{documentName}/swagger.json";
- })
- .UseSwaggerUI(options =>
- {
- options.SwaggerEndpoint("/SwaggerAPI01/swagger.json", "API01");
- });
- }
SwaggerOcelot,Starup.cs 配置
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddOcelotJwtAuthorize();
- // 注入 Ocelot
- services.AddOcelot(Configuration);
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
- services.AddSwaggerGen(options =>
- {
- options.SwaggerDoc("ApiGateway", new Info { Title = "网关服务", Version = "v1", Contact = new Contact { Email = "285130205@qq.com", Name = "SwaggerOcelot", Url = "http://10.10.10.10" }, Description = "网关平台" });
- });
- }
- public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- var apis = new Dictionary<string, string>(
- new KeyValuePair<string, string>[] {
- KeyValuePair.Create("SwaggerAuthorize", "Authorize"),
- KeyValuePair.Create("SwaggerAPI01", "API01"),
- KeyValuePair.Create("SwaggerAPI02", "API02")
- });
- app.UseMvc()
- .UseSwagger()
- .UseSwaggerUI(options =>
- {
- apis.Keys.ToList().ForEach(key =>
- {
- options.SwaggerEndpoint($"/{key}/swagger.json", $"{apis[key]} -[{key}]");
- });
- options.DocumentTitle = "Swagger 测试平台";
- });
- await app.UseOcelot();
- }
接下来, 为 Swagger 访问 Web API 项目, 添加请求返回格式, 默认状况下, Swagger 是支持 Json 的, 下来添加支持 XML 格式
第一步, 添加支持 XML 格式
- services.AddMvc()
- .AddXmlSerializerFormatters() // 设置支持 XML 格式输入输出
- .AddJsonOptions(op => op.SerializerSettings.ContractResolver = new DefaultContractResolver())// 大小写不转换
- .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
第二步, 在对应的 Action 添加 ProducesResponseType 特性, 为转换作支持
- [HttpGet("{id}")]
- [ProducesResponseType(typeof(API01Model), 200)]
- public ActionResult<API01Model> Get(int id)
- {
- return new API01Model { ID = 1, IsSure = true, Price = 2.3m, Describe = "test1" };
- }
运行效果:
先看登录
再看 api 访问
来源: https://www.cnblogs.com/axzxs2001/p/9253495.html