.NET Core和Swagger 生成 Api 文档转

前言

最近写了好多Web api, 老大说太乱了,要整理一下,使用Swagger。
花了半天的时间,在这里记录和分享一些过程和遇到的问题。html

遇到的主要问题:
1.localhost:9040/swagger/ not found
git

2.http://localhost:9040/swagger界面能够打开,可是can't read json file.
github

1.引用

这里引用了三个库,都是在Nuget上安装:
1.Microsoft.AspNetCore.StaticFiles, Version="2.0.3" , 这个package提供UI显示相关服务
2.Swashbuckle.AspNetCore, Version="2.4.0"
3.Swashbuckle.AspNetCore.SwaggerUi, Version="2.4.0"web

2.打开startup.cs文件

using Swashbuckle.AspNetCore.Swagger;

在ConfigureServices集合中注入AddSwaggerGen:json

public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Enable CORS services.AddCors(); //Inject Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "MyApi", Version = "v1" }); // Set the comments path for the Swagger JSON and UI. var xmlPath = Path.Combine(AppContext.BaseDirectory, "ChatBotApi.XML"); c.IncludeXmlComments(xmlPath); }); }

在Configure中启用中间件,容许Swagger提供服务生成json文档以及UI:swift

public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); app.UseStaticFiles(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; }); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { //c.RoutePrefix = "swagger/ui"; c.SwaggerEndpoint("v1/swagger.json", "ChatBotApi"); }); }

3.设置XML注释

在 Visual Studio 中右击项目而且选择 Properties 在 Output Settings 区域下面点击 XML Documentation file 。
api

这时候编译项目,会出现不少warning,提示api没有注释,在每一个Api controller上方,连续输入三个'/',便可将api的对应信息补充完整,要给每一个Api route加上 http的请求方式。
在各个Api里加上注释:浏览器

/// <summary> /// Put value by id and value /// </summary> /// <param name="id">id</param> /// <param name="value">value</param> /// PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } 

4.运行结果

1.在浏览器中输入:http://localhost:/swagger/v1/swagger.jsonapp

返回Json文档:

用json viewer打开json文件:

2.在浏览器输入:http://localhost:9040/swagger/

到此说明配置Swagger成功。

详细的API列表和文档说明:

5.主要问题的解决办法

1.RoutePrefix
这是个坑,要好好匹配当前的项目路径,否则UI打不开

2.SwaggerEndpoint
这是个坑,也是同样,若是路径匹配错误,UI打开了可是读取json文档失败。

这两个路径配置能够多试几回,我尝试了几十次~~

6.能够自定义UI

这个暂时没有作,今天太晚了,占个位置~

参考文档

1.Get started with Swashbuckle and ASP.NET Core
2.Swagger .NETCORE can't read json
3.ASP.NET Core 中文文档