NexusContract.OpenApi 1.0.0-preview.19

This is a prerelease version of NexusContract.OpenApi.
The owner has unlisted this package. This could mean that the package is deprecated, has security vulnerabilities or shouldn't be used anymore.
dotnet add package NexusContract.OpenApi --version 1.0.0-preview.19
                    
NuGet\Install-Package NexusContract.OpenApi -Version 1.0.0-preview.19
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NexusContract.OpenApi" Version="1.0.0-preview.19" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NexusContract.OpenApi" Version="1.0.0-preview.19" />
                    
Directory.Packages.props
<PackageReference Include="NexusContract.OpenApi" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add NexusContract.OpenApi --version 1.0.0-preview.19
                    
#r "nuget: NexusContract.OpenApi, 1.0.0-preview.19"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package NexusContract.OpenApi@1.0.0-preview.19
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=NexusContract.OpenApi&version=1.0.0-preview.19&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=NexusContract.OpenApi&version=1.0.0-preview.19&prerelease
                    
Install as a Cake Tool

NexusContract.OpenApi

为 NexusContract 元数据自动生成 OpenAPI/Swagger 文档

概述

NexusContract.OpenApi 将冻结的 NexusContract 元数据转换为 OpenAPI 规范,提供与 Swagger UI 的无缝集成,无需手动维护文档。

核心架构

┌─────────────────────────────────────────────┐
│  NexusContractMetadataRegistry(冻结)      │
│  - OperationId、HttpVerb、属性              │
│  - IsRequired、PropertySource、Description  │
└──────────────┬──────────────────────────────┘
         │
         └──→ NexusContractSwaggerDocumentFilter
           └─→ OpenAPI 文档 → Swagger UI

核心特性

1. 元数据 DNA 提取

  • 自动从 NexusContractMetadataRegistry 读取所有冻结的契约元数据
  • 将元数据转换为 OpenAPI 路径、操作、参数、响应定义

2. 文档即真实

  • 100% 的文档来自运行时元数据
  • 文档始终与实际 API 行为保持同步
  • 必填字段、参数位置、类型自动反映

3. 错误码集成

  • 在 OpenAPI 响应定义中包含 NXC 诊断代码
  • 将错误码映射到 HTTP 状态码(NXC1xx → 400,NXC5xx → 500)
  • 为开发者提供完整的错误文档

4. 类型推断

  • 自动从 IApiRequest<TResponse> 泛型推断响应类型
  • 生成复杂类型的正确 JSON Schema
  • 支持数组、枚举和嵌套对象

使用指南

安装和配置

// 在 Program.cs 中
var builder = WebApplication.CreateBuilder(args);

// 注册 Swagger + NexusContract OpenAPI
builder.Services
    .AddSwaggerGen()  // Swashbuckle 基础注册
    .AddNexusOpenApi(options =>
    {
        // 必须与 Hosting 的基础路由相匹配
        options.BaseRoute = "/v3";
    });

var app = builder.Build();

// 启用 Swagger UI
app.UseSwagger();
app.UseSwaggerUI();

// 注册端点(基础路由必须与 OpenAPI BaseRoute 相匹配)
app.MapNexusEndpoints("/v3");

app.Run();

快速设置(一行代码)

builder.Services.AddNexusSwagger();  // 组合 AddSwaggerGen + AddNexusOpenApi

高级配置

builder.Services.AddNexusOpenApi(options =>
{
    options.IncludeNxcErrorCodes = true;      // 显示 NXC 错误码
    options.GenerateExamples = true;           // 生成示例值
    options.MarkRequiredFields = true;         // 标记必填字段
    options.DocumentTitle = "我的支付 API";
    options.DocumentVersion = "v2.0";
    options.DocumentDescription = "支付处理 API";
    options.BaseRoute = "/v3";
});

生成的 OpenAPI 结构

路径项

对于每个带有 [ApiOperation] 的契约:

{baseRoute}/{provider}/{profileId}/{operationTail}
    ├── 200: 成功(带推断的响应类型 Schema)
    ├── 400: 请求错误(NXC1xx 验证错误)
    └── 500: 服务器错误(NXC5xx 框架错误)

Schema 生成规则

C# 类型 OpenAPI Schema
string type: string
int, long type: integer, format: int64
decimal, double type: number, format: double
bool type: boolean
DateTime type: string, format: date-time
List<T>, T[] type: array, items: {T 的 Schema}
自定义类 type: object(包含属性)

实战示例

契约定义

[ApiOperation("alipay.trade.create", HttpVerb.POST)]
public class TradeCreateRequest : IApiRequest<TradeCreateResponse>
{
    [ApiField("out_trade_no", PropertySource.Body, IsRequired = true)]
    public string OutTradeNo { get; set; }

    [ApiField("total_amount", PropertySource.Body, IsRequired = true)]
    public string TotalAmount { get; set; }

    [ApiField("subject", PropertySource.Body, IsRequired = true)]
    public string Subject { get; set; }
}

public class TradeCreateResponse
{
    public string TradeNo { get; set; }
    public string Status { get; set; }
}

生成的 OpenAPI 文档

paths:
  /api/gateway/alipay/trade/create:
    post:
      operationId: mirror_alipay.trade.create
      summary: alipay.trade.create
      tags:
        - alipay
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                out_trade_no:
                  type: string
                total_amount:
                  type: string
                subject:
                  type: string
              required:
                - out_trade_no
                - total_amount
                - subject
      responses:
        '200':
          description: 成功
          content:
            application/json:
              schema:
                type: object
                properties:
                  tradeNo:
                    type: string
                  status:
                    type: string
        '400':
          description: 请求无效(NXC1xx 验证错误)
        '500':
          description: 服务器错误(NXC5xx 框架错误)

NXC 错误码集成

过滤器自动为所有 NXC 诊断代码注册错误响应 Schema:

  • NXC101:缺少 [ApiOperation] 属性
  • NXC102:缺少 [ApiField] 属性
  • NXC110:必填字段缺失
  • NXC111:需要加密但未提供加密器
  • NXC201:无效的 URL 参数
  • NXC504:启动时元数据未预加载
  • NXC999:框架内部错误

这些错误被映射到 OpenAPI 文档中的响应定义,为开发者提供完整的错误文档。

设计原则

1. 单一职责

  • OpenAPI 层与 Hosting 和 Core 层分离
  • 专注于元数据→文档的转换

2. 零重复

  • 文档 100% 来自元数据
  • 无需单独的文档定义、配置或注解

3. 类型安全

  • 通过泛型 IApiRequest<TResponse> 实现强类型
  • Schema 生成完全自动化

4. 可扩展性

  • NexusOpenApiOptions 允许自定义
  • IDocumentFilter 模式支持未来扩展

架构决策

为什么独立 NexusContract.OpenApi?

  1. 解耦:文档生成独立于运行时路由
  2. 可选依赖:不使用 Swagger 的项目可以跳过此 NuGet
  3. 聚焦测试:OpenAPI 逻辑可独立测试
  4. 职责清晰:Core 处理元数据,OpenApi 处理文档

为什么不在 NexusContract.Hosting 中?

  • Hosting 层应专注于请求/响应管道
  • Swagger 是可选的(不是所有 API 都需要 OpenAPI 文档)
  • 关注点分离提高可维护性

参考资源

许可证

MIT 许可证 - 详见项目根目录的 LICENSE 文件

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated

v1.0: Initial release. Automatic OpenAPI document generation from NexusContractMetadataRegistry. Supports parameter extraction, response mapping, and error code integration.