ASP.NET Core WebApi使用Swagger生成API说明文档【xml注释版】
2023-09-11 14:18:14 时间
⒈新建ASP.NET Core WebAPi项目
⒉添加 NuGet 包
Install-Package Swashbuckle.AspNetCore
⒊Startup中配置
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading.Tasks; 5 using Microsoft.AspNetCore.Builder; 6 using Microsoft.AspNetCore.Hosting; 7 using Microsoft.AspNetCore.Mvc; 8 using Microsoft.Extensions.Configuration; 9 using Microsoft.Extensions.DependencyInjection; 10 using Microsoft.Extensions.Logging; 11 using Microsoft.Extensions.Options; 12 using Swashbuckle.AspNetCore.Swagger; 13 14 namespace SwaggerXmlDemo 15 { 16 public class Startup 17 { 18 public Startup(IConfiguration configuration) 19 { 20 Configuration = configuration; 21 } 22 23 public IConfiguration Configuration { get; } 24 25 // This method gets called by the runtime. Use this method to add services to the container. 26 public void ConfigureServices(IServiceCollection services) 27 { 28 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 29 30 //注册Swagger生成器,定义一个和多个Swagger 文档 31 services.AddSwaggerGen(option => 32 { 33 //配置第一个Doc 34 option.SwaggerDoc("v1", new Info 35 { 36 Version = "v1", 37 Title = "My API_1", 38 Description = "Document Api", 39 Contact = new Contact 40 { 41 Name = "fanqi", 42 Email = "fanqisoft@163.com", 43 Url = "https://www.coreqi.cn" 44 } 45 }); 46 }); 47 } 48 49 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 50 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 51 { 52 if (env.IsDevelopment()) 53 { 54 app.UseDeveloperExceptionPage(); 55 } 56 57 //启用中间件服务生成Swagger作为JSON终结点 58 app.UseSwagger(); 59 60 //启用中间件服务对swagger-ui,指定Swagger JSON终结点 61 app.UseSwaggerUI(c => 62 { 63 c.SwaggerEndpoint("/swagger/v1/swagger.json", "DemoAPI V1"); 64 //c.RoutePrefix = "swagger"; //默认 65 c.RoutePrefix = string.Empty; 66 }); 67 68 app.UseMvc(); 69 } 70 } 71 }
⒋添加注释信息
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading.Tasks; 5 6 namespace SwaggerXmlDemo.Models 7 { 8 /// <summary> 9 /// 用户实体类 10 /// </summary> 11 public class User 12 { 13 /// <summary> 14 /// 用户主键Id 15 /// </summary> 16 /// <example>1</example> 17 public int id { get; set; } 18 /// <summary> 19 /// 用户名 20 /// </summary> 21 /// <example>fanqi</example> 22 public string username { get; set; } 23 /// <summary> 24 /// 用户密码 25 /// </summary> 26 /// <example>admin</example> 27 public string password { get; set; } 28 /// <summary> 29 /// 用户年龄 30 /// </summary> 31 /// <example>25</example> 32 public int? age { get; set; } 33 /// <summary> 34 /// 用户邮箱 35 /// </summary> 36 /// <example>fanqisoft@163.com</example> 37 public string email { get; set; } 38 } 39 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading.Tasks; 5 using Microsoft.AspNetCore.Http; 6 using Microsoft.AspNetCore.Mvc; 7 using SwaggerXmlDemo.Models; 8 9 namespace SwaggerDemo.Controllers 10 { 11 /// <summary> 12 /// 用户Api控制器 13 /// </summary> 14 [Route("api/[controller]")] 15 [ApiController] 16 public class UserController : ControllerBase 17 { 18 /// <summary> 19 /// 获取系统用户列表 20 /// </summary> 21 /// <remarks> 22 /// Demo 23 /// Get /api/user/get 24 /// </remarks> 25 /// <returns>系统用户列表</returns> 26 /// <response code="201">返回用户列表</response> 27 /// <response code="401">没有权限</response> 28 [HttpGet("get")] 29 [ProducesResponseType(201)] 30 [ProducesResponseType(401)] 31 public IList<User> GetUsers() 32 { 33 return new List<User> 34 { 35 new User{ id = 1,username = "fanqi",password = "admin",age = 25,email = "fanqisoft@163.com"}, 36 new User{ id = 2,username = "gaoxing",password = "admin",age = 22,email = "gaoxing@163.com"} 37 }; 38 } 39 40 /// <summary> 41 /// 新建用户 42 /// </summary> 43 /// <param name="user">新建用户信息</param> 44 /// <returns>是否创建成功信息</returns> 45 [HttpPost("add")] 46 public IActionResult CreateUser([FromForm] User user) 47 { 48 return Ok(); 49 } 50 } 51 }
⒋启用XML注释
1.右键单击“解决方案资源管理器”中的项目,然后选择“属性”
2.勾选“生成”选项卡“输出”部分的“XML 文档文件”框
右键生成的XML文件,选择属性。修改“复制到输出目录”为“始终复制”。
启用 XML 注释后会为未记录的公共类型和成员提供调试信息将会出现很多CS1591警告信息。直接无视即可。
警告 CS1591 缺少对公共可见类型或成员“xxxxx”的 XML 注释 指定了 /doc 编译器选项,但是一个或多个构造没有注释。
如果有强迫症,可以按照下图所示进行取消
注意上面生成的xml文档文件的路径,
注意:
1.对于 Linux 或非 Windows 操作系统,文件名和路径区分大小写。 例如,“SwaggerDemo.xml”文件在 Windows 上有效,但在 CentOS 上无效。
2.获取应用程序路径,建议采用
Path.GetDirectoryName(typeof(Program).Assembly.Location)
这种方式或者·AppContext.BaseDirectory这样来获取
⒌为 Swagger JSON和UI设置xml文档注释路径
1 // This method gets called by the runtime. Use this method to add services to the container. 2 public void ConfigureServices(IServiceCollection services) 3 { 4 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 5 6 //注册Swagger生成器,定义一个和多个Swagger 文档 7 services.AddSwaggerGen(option => 8 { 9 //配置第一个Doc 10 option.SwaggerDoc("v1", new Info 11 { 12 Version = "v1", 13 Title = "My API_1", 14 Description = "Document Api", 15 Contact = new Contact 16 { 17 Name = "fanqi", 18 Email = "fanqisoft@163.com", 19 Url = "https://www.coreqi.cn" 20 } 21 }); 22 23 // 为 Swagger JSON and UI设置xml文档注释路径 24 //var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径) 25 //var xmlPath = Path.Combine(basePath, "SwaggerXmlDemo.xml"); 26 var filePath = Path.Combine(System.AppContext.BaseDirectory, "SwaggerXmlDemo.xml"); 27 option.IncludeXmlComments(filePath); 28 }); 29 }
⒍查看效果
相关文章
- .NET平台开源项目速览(12)哈希算法集合类库HashLib
- Sandcastle方法生成c#.net帮助类帮助文档chm
- 使用 Visual Studio 部署 .NET Core 应用 ——.Net Core 部署到SUSE Linux Enterprise Server 12 SP2 64 位(GNOME 版本3.20.2)
- C#.Net实体代码生成工具(EntitysCodeGenerate)的使用及.NET中的ORM实现
- 《ASP.NET MVC4 WEB编程》学习笔记------.net mvc实现原理ActionResult/View
- Client使用c#和odp.net连接server oracle
- Asp.Net Web API 2第十七课——Creating an OData Endpoint in ASP.NET Web API 2(OData终结点)
- 集成Swagger接口文档分组配置.net core
- 重新整理 .net core 实践篇————配置应用[一]
- .net 4种单例模式
- 重新整理 .net core 实践篇—————应用层[三十]
- [ASP.NET Core 3框架揭秘] 配置[5]:配置数据与数据源的实时同步
- TechEmpower最新一轮的性能测试出炉,ASP.NET Core依旧表现不俗
- 利用ArcGIS Engine、VS .NET和Windows控件开发GIS应用
- 这些.NET开源项目你知道吗?.NET平台开源文档与报表处理组件集合(三)
- Atitit ..Net Framework sdk 3.0 3.5 4.04.5 4.6 4.7 .net core版本新特性 v2 s22 1. 新特性来源于 down ms 官方网站1
- Atitit.upnp SSDP 查找nas的原理与实现java php c#.net c++
- Atitit。D&D drag&drop拖拽功能c#.net java swing的对比与实现总结
- 你的NET程序需要保护吗?Agile.net 6.6.X 注入式Crack
- VB.net:VB.net编程语言学习之基于VS软件连接SQL Server(利用ADO.NET操作数据库/添加新数据源/DataGridView数据表格控件)的简介、案例应用之详细攻略
- ASP.NET Core微服务(六)——【.Net Core操作redis】StackExchange.Redis
- . net core的发布
- [C#.NET 拾遗补漏]10:理解 volatile 关键字
- VB.net:VB.net编程语言学习之基于VS软件连接SQL Server(利用ADO.NET操作数据库/添加新数据源/DataGridView数据表格控件)的简介、案例应用之详细攻略
- net core HTTP Error 500.31 - Failed to load ASP.NET Core runtime HTTP Error 500.30