工作中遇到前后端分离项目,会有接口对接方面的需要,在项目里引用了Swagger,用来查看、测试Web接口
项目环境: .net core 3.1
开发工具:VS 2019
项目引用相关包:
Swashbuckle.AspNetCore 5.4.1
Swashbuckle.AspNetCore.Annotations 5.4.1
在项目初始化时注入相关服务 ,修改Startup.cs文件
using Microsoft.Extensions.Hosting; using Microsoft.AspNetCore.Hosting; using Swashbuckle.AspNetCore.Swagger; public void ConfigureServices(IServiceCollection services) { services.AddCustomizedSwaggerGen();// #增加SwaggerGen services.AddControllers(); services.AddCors(option => option.AddPolicy("cors", policy => policy.AllowAnyOrigin())); #接口跨域时,会用到该配置。默认不需要 } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseCustomizedSwagger(env);// #增加SwaggerGen ,传入环境参数env }
增加帮助类 SwaggerExtensions.cs
using System.Linq; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Swashbuckle.AspNetCore.SwaggerGen; public static class SwashbuckleSwaggerExtensions { public static IServiceCollection AddCustomizedSwaggerGen(this IServiceCollection services) { services.AddSwaggerGen(options => { foreach (var doc in _docs) options.SwaggerDoc(doc, new OpenApiInfo { Version = doc }); options.DocInclusionPredicate((docName, apiDesc) => { if (apiDesc.TryGetMethodInfo(out var method) == false) return false; var versions = method.DeclaringType.GetCustomAttributes(false) .OfType<ApiExplorerSettingsAttribute>() .Select(attr => attr.GroupName); if (docName == "未分类" && versions.Count() == 0) return true; return versions.Any(v => v == docName); }); options.IgnoreObsoleteActions(); //options.IgnoreObsoleteControllers(); // 类、方法标记 [Obsolete],可以阻止【Swagger文档】生成 //options.EnableAnnotations(); options.DescribeAllEnumsAsStrings(); options.CustomSchemaIds(a => a.FullName); options.OperationFilter<FormDataOperationFilter>(); }); return services; } static string[] _docs = new[] { "webapi", "webui" }; public static IApplicationBuilder UseCustomizedSwagger(this IApplicationBuilder app, IWebHostEnvironment env) { return app.UseSwagger().UseSwaggerUI(options => { foreach (var doc in _docs) options.SwaggerEndpoint($"/swagger/{doc}/swagger.json", doc); }); } }
增加筛选器
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; public class FormDataOperationFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { } }
相关配置已经完成。 接下来对代码增加标记
using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; [HttpGet("LoginCheck"), SwaggerOperation(Tags = new[] { "LoginCheck" })] public string loginCheck(string jwt) { #逻辑代码 } [HttpGet, SwaggerOperation(Tags = new[] { "查询事件接口" })] public AjaxResult Get(string day_id01 = "") { #逻辑代码 }
运行如下