将 NSwag 用于 .NET Core 3.1 的简洁而简单的方法。只需添加下面的代码,您就可以对控制器和 API 进行很好的描述。在 swagger 页面的顶部加上一些描述。
Startup.cs - 方法:public void ConfigureServices(IServiceCollection services)
services.AddSwaggerDocument(config =>
{
config.OperationProcessors.Add(
new AspNetCoreOperationSecurityScopeProcessor("JWT"));
// Add summary to the controller
config.UseControllerSummaryAsTagDescription = true;
// Add JWT authorization option at the top
config.AddSecurity("JWT", Enumerable.Empty<string>(), new OpenApiSecurityScheme
{
Type = OpenApiSecuritySchemeType.ApiKey,
Name = "Authorization",
In = OpenApiSecurityApiKeyLocation.Header,
Description = "Type into the textbox: Bearer {your JWT Token}"
});
config.PostProcess = document =>
{
document.Info.Version = "1";
document.Info.Title = "title";
document.Info.Description = "description";
};
});
方法:public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
添加这个:
//CONFIG: Configure NSwag
app.UseOpenApi();
app.UseSwaggerUi3();
然后,在控制器类和方法的顶部,只需添加一个摘要,例如:
/// <summary>
/// your description
/// </summary>
[ApiController]
[Route(your route)]
public class NameController : ControllerBase
它会像现场演示一样干净整洁:https://swagger.io/tools/swagger-ui/