aspdot core 添加 swagger
命令行中执行:
dotnet add TodoApi.csproj package Swashbuckle.AspNetCore
dotnet core 2.0会自动安装所需要的包文件
将 Swagger 生成器添加到 Startup.cs 的 ConfigureServices
方法中的服务集合:
using Swashbuckle.AspNetCore.Swagger; public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Register the Swagger generator, defining one or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); }
在 Startup.cs 的 Configure
方法中,启用中间件为生成的 JSON 文档和 SwaggerUI 提供服务:
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(); }
Swagger UI,可以通过导航到 http://localhost:<random_port>/swagger
进行查看:
============================================================================================================================================
设置swagger 支持 /// 三斜杠注释:
在 .csproj 文件中增加
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>bin\Debug\netcoreapp2.0\ContosoUniversity.xml</DocumentationFile> </PropertyGroup>
注:ContosoUniversity.xml 根据项目不同,名称不同
在 Startup.cs 文件中,修改 ConfigureServices 方法,增加代码:
// Register the Swagger generator, defining one 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 = "", 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 basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "TodoApi.xml"); c.IncludeXmlComments(xmlPath); });
增加方法 /// 注释,并在 swagger 中查看
Swagger 文件夹解压到wwwroot 目录下。
在 Startup.cs 文件中,Configure 启动静态文件加载.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); app.UseStaticFiles(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Billing API V1"); }); app.UseMvc(); }
在项目配置中,设置 debug 启动路径为: swagger/ui/index.html