官方文档地址
https://docs.microsoft.com/zh-cn/aspnet/?view=aspnetcore-2.2#pivot=core
使用 ASP.NET Core 构建 Web API
添加API 控制器
[Route("api/[controller]/[action]")] [ApiController] public class HomeController : ControllerBase
设置默认API
修改launchSetting.json 的launchUrl 设置默认路由
{ "profiles": { "CoreWebAPI": { "commandName": "Project", "launchBrowser": true, "launchUrl": "api/Home/Index", "applicationUrl": "http://localhost:5124", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
Swashbuckle
安装Nuget 包 Swashbuckle.AspNetCore
Install-Package Swashbuckle.AspNetCore
添加并配置 Swagger 中间件
将 Swagger 生成器添加到 Startup.ConfigureServices
方法中的服务集合中:
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); });
在 Startup.Configure
方法中,启用中间件为生成的 JSON 文档和 Swagger UI 提供服务
public void Configure(IApplicationBuilder app) { // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseMvc(); }
要在应用的根 (http://localhost:<port>/
) 处提供 Swagger UI,请将 RoutePrefix
属性设置为空字符串:
app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); c.RoutePrefix = string.Empty; });
API 信息和说明
// Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "ToDo API", Description = "A simple example ASP.NET Core Web API", TermsOfService = "None", Contact = new Contact { Name = "Shayne Boyer", Email = string.Empty, Url = "https://twitter.com/spboyer" }, License = new License { Name = "Use under LICX", Url = "https://example.com/license" } }); });
Swagger UI 显示注释
- 在“解决方案资源管理器”中右键单击该项目,然后选择“编辑 <project_name>.csproj”。
- 手动将突出显示的行添加到 .csproj 文件
<PropertyGroup> <GenerateDocumentationFile>true</GenerateDocumentationFile> <NoWarn>$(NoWarn);1591</NoWarn> </PropertyGroup>
在Service 配置swagger.xml 文件
// Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "ToDo API", Description = "A simple example ASP.NET Core Web API", TermsOfService = "None", Contact = new Contact { Name = "Shayne Boyer", Email = string.Empty, Url = "https://twitter.com/spboyer" }, License = new License { Name = "Use under LICX", Url = "https://example.com/license" } }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); });