Swagger UI 及Swashbuckle
一、概念:
由Swagger网站可知,Swagger是展示RESTful API的简单而强大的方法,它为此API提供了强大的接口。
由Swashbuckle GitHub可知,Swashbuckle可将Swagger无缝添加到WebApi中!将ApiExplorer与Swagger/swagge-ui 合并可以给 API 用户带来丰富的探索、文件和操作体验。除Swagger生成器外,Swashbuckle还包含嵌入式版本的swagger-ui。
二、使用
1、使用包命令添加到项目
install-package Swashbuckle,会自动检测当前项目的环境添加依赖项。
2、生成xml文档文件
项目属性->勾选生成xml文档文件
3、修改SwaggerConfig文件,设置接口描述xml路径地址
c.IncludeXmlComments($"{System.AppDomain.CurrentDomain.BaseDirectory}/bin/{thisAssembly.GetName().Name}.XML");
4、汉化
a、添加自定义JS汉化包。
b、加载自定义汉化包:
//路径规则,项目命名空间.文件夹名称.js文件名称
c.InjectJavaScript(thisAssembly, "Unisoft.WeChat.Content.swaggerui.swagger_lang.js");
具体参考:http://www.cnblogs.com/yanweidie/p/5709113.html
5、自定义参数及OAuth2授权
a、自定义参数代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | /// <summary> /// 自定义参数 /// </summary> public class CustomParameterFilter : IOperationFilter { public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { if (operation.parameters == null ) operation.parameters = new List<Parameter>(); var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline(); //判断是否添加权限过滤器 var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Instance).Any(filter => filter is IAuthorizationFilter); //判断是否允许匿名方法 var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any(); //不含请求参数 if (!operation.parameters.Any()) { //判断是否为POST请求 var isPost = apiDescription.HttpMethod.Method.ToLower() == "post" ; if (isPost) { //添加POST参数 operation.parameters.Add( new Parameter { name = "body" , @ in = "body" , description = "test" , required = false }); } } //添加认证参数 if (isAuthorized && !allowAnonymous) { operation.parameters.Add( new Parameter { name = "token" , @ in = "query" , description = "认证参数" , required = true , type = "string" , @ default = "Unisoft@qodlALKJ8Fack123" }); } } } |
b、使用自定义参数
c.OperationFilter<CustomParameterFilter>();
具体参考:https://stackoverflow.com/questions/28033857/web-api-with-oauth-using-swagger-swashbuckle
其它资料参考:https://www.codeproject.com/Articles/1078249/RESTful-Web-API-Help-Documentation-using-Swagger-U#_articleTop
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
· 本地部署 DeepSeek:小白也能轻松搞定!
· 基于DeepSeek R1 满血版大模型的个人知识库,回答都源自对你专属文件的深度学习。
· 在缓慢中沉淀,在挑战中重生!2024个人总结!
· 大人,时代变了! 赶快把自有业务的本地AI“模型”训练起来!
· Tinyfox 简易教程-1:Hello World!