You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Swagger-UI中基于OpenAPI文档生成随机GUID?

问题描述

我拥有一份OpenAPI文档,希望在Swagger-UI中为format: guid的字段生成随机GUID,但目前工具生成的是无格式的普通字符串。

对应的OpenAPI片段:

{
    "id": {
      "type": "string",
      "format": "guid"
    }
}

我的ASP.NET Core项目中NSwag配置代码如下:

app.UseSwaggerUi3(settings =>
{
    settings.DocumentPath = $"/{pathBase}/api/specification.json";
});

app.UseOpenApi();

services.AddOpenApiDocument((configure, sp) =>
{
    var config = sp.CreateScope().ServiceProvider
        .GetRequiredService<IConfiguration>();

    configure.PostProcess = d =>
    {
        d.Servers.Add(new NSwag.OpenApiServer { Url = $"/{config["SwaggerBasePath"]}" });
        d.Servers.Add(new NSwag.OpenApiServer { Url = "/" });
    };
    // Add the fluent validations schema processor
    var fluentValidationSchemaProcessor =
        sp.CreateScope().ServiceProvider.GetRequiredService<FluentValidationSchemaProcessor>();

    configure.SchemaSettings.SchemaProcessors.Add(fluentValidationSchemaProcessor);
    configure.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("JWT"));
});
解决方案

要实现Swagger-UI自动生成随机GUID,只需在NSwag的文档配置中,为guid格式的字符串添加自定义示例生成逻辑:

  1. 在AddOpenApiDocument的配置委托中,修改SchemaSettings,添加针对guid格式的字符串生成器:
configure.SchemaSettings.StringFormatGenerators.Add("guid", () => Guid.NewGuid().ToString());
  1. 修改后的完整配置代码:
services.AddOpenApiDocument((configure, sp) =>
{
    var config = sp.CreateScope().ServiceProvider
        .GetRequiredService<IConfiguration>();

    configure.PostProcess = d =>
    {
        d.Servers.Add(new NSwag.OpenApiServer { Url = $"/{config["SwaggerBasePath"]}" });
        d.Servers.Add(new NSwag.OpenApiServer { Url = "/" });
    };
    // Add the fluent validations schema processor
    var fluentValidationSchemaProcessor =
        sp.CreateScope().ServiceProvider.GetRequiredService<FluentValidationSchemaProcessor>();

    configure.SchemaSettings.SchemaProcessors.Add(fluentValidationSchemaProcessor);
    configure.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("JWT"));

    // 配置guid格式字段生成随机GUID示例
    configure.SchemaSettings.StringFormatGenerators.Add("guid", () => Guid.NewGuid().ToString());
});

这段代码会让NSwag在生成OpenAPI文档时,为所有format: guid的字符串字段自动生成随机的GUID值作为示例,Swagger-UI就会使用这个随机GUID作为请求示例内容。

内容的提问来源于stack exchange,提问作者Oleg Pro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 01:25:07