杨钫涵个人资料,辽工大素质拓展网,青岛大学录取结果查询
Swagger也算是行之有年的API文件生成器,只要在API上使用C#的<summary />
文件注解标签,就可以产生精美的线上文件,并且对RESTful API有良好的支持。不仅支持生成文件,还支持模拟调用的交互功能,连Postman都不用打开就能测API。
本篇将介绍如何通过Swagger产生ASP.NET Core的RESTful API文件。
要在ASP.NET Core使用Swagger需要安装Swashbuckle.AspNetCore
套件。
通过过.NET Core CLI在项目文件夹执行安装指令:
dotnet add package Swashbuckle.AspNetCore
在Startup.cs
的ConfigureServices
加入Swagger的服务及Middleware。如下:
using Swashbuckle.AspNetCore.Swagger; // ... public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc() .AddJsonOptions(options => { options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; }); services.AddSwaggerGen(c => { c.SwaggerDoc( // name: 关系到 SwaggerDocument 的 URL 位置。 name: "v1", // info: 是用于 SwaggerDocument 版本信息的提示(內容非必填)。 info: new Info { Title = "RESTful API", Version = "1.0.0", Description = "This is ASP.NET Core RESTful API Sample.", TermsOfService = "None", Contact = new Contact { Name = "SnailDev", Url = "http://www.cnblogs.com/snaildev/" }, License = new License { Name = "CC BY-NC-SA 4.0", Url = "https://creativecommons.org/licenses/by-nc-sa/4.0/" } } ); }); } public void Configure(IApplicationBuilder app) { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint( // url: 需配合 SwaggerDoc 的 name。 "/swagger/{SwaggerDoc name}/swagger.json" url: "/swagger/v1/swagger.json", // name: 用于 Swagger UI 右上角选择不同版本的 SwaggerDocument 提示名称使用。 name: "RESTful API v1.0.0" ); }); app.UseMvc(); } }
SwaggerDocument
物件。SwaggerDocument
物件。SwaggerDocument
物件。http://localhost:5000/swagger/v1/swagger.json
SwaggerDocument
物件变成漂亮的界面。http://www.lhsxpumps.com/_localhost:5000/swagger
API沿用的示例程序。
设定完成后,启动网站就能开启Swagger UI 了。下面如下:
在API加入<summary />
文件注解标签。如下:
// ... [Route("api/[controller]s")] public class UserController : Controller { /// <summary> /// 查询使用者清单 /// </summary> /// <param name="q">查询使用者名称</param> /// <returns>使用者清单</returns> [HttpGet] public ResultModel Get(string q) { // ... } }
再次打开Swagger,会发现没有显示说明,因为没有设定.NET 的XML 文件目录,所以Swagger 抓不到说明是正常的。
打开*.csproj
,在<Project />
区块中插入以下代码:
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>bin\Debug\netcoreapp2.0\Api.xml</DocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup>
以我示例的*.csproj
内容如下:
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp2.0</TargetFramework> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>bin\Debug\netcoreapp2.0\Api.xml</DocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup> <ItemGroup> <Folder Include="wwwroot\" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.8" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="2.5.0" /> </ItemGroup> </Project>
然后在Swagger生成器设定读取<DocumentationFile>
指定的XML文件目录位置:
// ... public class Startup { public void ConfigureServices(IServiceCollection services) { // ... services.AddSwaggerGen(c => { // ... var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Api.xml"); c.IncludeXmlComments(filePath); }); } }
以RESTful API的例子来看,返回的格式都是JSON,所以可以直接在Controller加上[Produces("application/json")]
表示返回的类型都是JSON,在Swagger的Response Content Type选项就会被锁定只有application/json可以使用。如下:
// ... [Route("api/[controller]s")] [Produces("application/json")] public class UserController : Controller { // ... }
若有预期API在不同的HTTP Status Code时,会返回不同的对象,可以透过[ProducesResponseType(type)]
定义返回的对象。在Swagger中就可以清楚看到该API可能会发生的HTTP Status Code及返回对象。例如:
// ... [Route("api/[controller]s")] [Produces("application/json")] public class UserController : Controller { /// <summary> /// 查询使用者清单 /// </summary> /// <param name="q">查询使用者名称</param> /// <returns>使用者清单</returns> [HttpGet] [ProducesResponseType(typeof(ResultModel<IEnumerable<UserModel>>), 200)] [ProducesResponseType(typeof(ResultModel<string>), 500)] public ResultModel<IEnumerable<UserModel>> Get(string q) { // ... } }
老司机发车啦:
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Net Core Web Api项目与在NginX下发布的方法
asp.net core3.1 引用的元包dll版本兼容性问题解决方案
IdentityServer4实现.Net Core API接口权限认证(快速入门)
ASP.NET Core MVC通过IViewLocationExpander扩展视图搜索路径的实现
网友评论