Skip to content

Fast.Swagger

逐成员 API、参数与返回参考

版本 3.5.34;目标 net8.0net9.0net10.0;依赖 Fast.RuntimeFast.DynamicApplication 与 Swashbuckle.AspNetCore(源中央版本 10.2.3)。提供 Swagger JSON、分组与 UI,不等同于客户端代码生成。

bash
dotnet add package Fast.Swagger

注册与中间件

csharp
using Fast.Swagger;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSwaggerDocuments(builder.Configuration);
var app = builder.Build();
app.UseSwaggerDocuments();
app.MapControllers();
app.Run();
签名行为
AddSwaggerDocuments(IServiceCollection, IConfiguration, string section = "SwaggerSettings", Action<SwaggerGenOptions> configure = null)绑定、后配置选项,注册 API Explorer 和启用时的 SwaggerGen
AddSwaggerDocuments(IServiceCollection, Action<SwaggerSettingsOptions>, Action<SwaggerGenOptions> configure = null)回调生成独立设置,当前实现不调用 PostConfigure;不能假定与配置节点重载默认值等价
UseSwaggerDocuments(IApplicationBuilder, Action<SwaggerOptions> configure = null, Action<SwaggerUIOptions> configureUI = null)按 Enable 配置 JSON 与 UI 中间件,返回 app

首选配置节点重载展示默认行为。若使用回调重载,需显式调用 options.PostConfigure() 或完整设置所需字段;否则 Enable 等可空字段尚无默认值。

SwaggerSettingsOptions

字段后配置默认值 / 用途
Enabletrue
DocumentTitle / DefaultGroupNameSpecification Api Document / Default
EnableAuthorizedtrue,配置文档中的授权定义,不等同于保护文档访问
FormatAsV2false
RouteTemplateswagger/{documentName}/swagger.json
RoutePrefix设置 UI 前缀;未配置时 BuildUI 使用空字符串,UI 位于站点根路径
DocExpansionStateList
XmlComments从项目程序集收集 XML 文件列表
GroupOpenApiInfos默认包含 DefaultGroupName 分组
Servers / PackagesGroups空数组
HideServerstrue
EnableEnumSchemaFilter / EnableTagsOrderDocumentFiltertrue
EnableAllGroups / EnumToNumberfalse
SecurityDefinitionsServerDirLoginInfo安全定义、服务目录、登录展示相关配置,不能代替应用授权

其他公开入口

SwaggerDocumentBuilder 提供 DocumentGroupsGetOpenApiGroupsGetGroupOpenApiInfoCheckApiDescriptionInCurrentGroupGetControllerGroups/GetActionGroupsGetControllerTag/GetActionTagIsApiAction 等分组/描述查询。它们依赖已初始化的应用描述上下文,不是脱离 MVC 的纯字符串工具。

SchemaIdAttributeOperationIdAttribute 固定 Schema/操作标识;SwaggerOpenApiInfoSwaggerOpenApiSecuritySchemeSwaggerOpenApiSecurityRequirementItemSwaggerLoginInfoGroupExtraInfoISwaggerOptions 是对应配置/扩展模型。

控制器与文档描述

上方代码放在消费端 Program.cs,项目采用 Microsoft.NET.Sdk.Web,目标为本页支持的 .NET 8/9/10。再添加以下控制器;宿主实际启动后可用 Swagger UI 查看方法、参数与响应类型。文档维护不会启动服务或请求 JSON。

csharp
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/catalog")]
public sealed class CatalogController : ControllerBase
{
    [HttpGet("{id:int}")]
    [ProducesResponseType(typeof(CatalogItem), 200)]
    public ActionResult<CatalogItem> Get(int id) => new CatalogItem(id, "示例商品");
}

public sealed record CatalogItem(int Id, string Name);

返回类型与响应特性参与文档生成,但不自动验证接口实现一定返回该状态码。是否启用 UI、文档分组与访问路径由本页的 SwaggerSettingsOptions 决定;生产环境应按应用授权策略控制暴露范围。

来源与验证

依据 注册重载选项。本轮未编译新增片段或访问 Swagger 服务;已有入门示例的历史编译记录不替代本页新增配置验证。