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

如何在Nancy.Swagger构建的Swagger-UI中添加参数示例值?

解决Nancy.Swagger请求体对象属性示例值不显示的问题

我之前也踩过这个坑!Nancy.Swagger默认只会给属性显示类型占位符(比如string),要替换成真实示例值,有两种实用的方法,你可以根据场景选:

方法1:自定义模型数据构建器(全局生效)

如果想让所有同类型的属性都自动带上示例,或者统一处理模型的示例逻辑,自定义ISwaggerModelDataBuilder是最方便的:

  1. 创建一个继承自默认实现的构建器类:
public class CustomSwaggerModelDataBuilder : DefaultSwaggerModelDataBuilder
{
    protected override SwaggerPropertyData CreatePropertyData(PropertyInfo property)
    {
        var propertyData = base.CreatePropertyData(property);
        
        // 给字符串类型的属性设置默认示例,你可以根据类型/属性名自定义
        if (property.PropertyType == typeof(string))
        {
            // 比如根据属性名判断:如果是Name就设为"张三",Email设为"example@test.com"
            switch (property.Name)
            {
                case "Name":
                    propertyData.Example = "张三";
                    break;
                case "Email":
                    propertyData.Example = "example@test.com";
                    break;
                default:
                    propertyData.Example = "自定义示例文本";
                    break;
            }
        }
        // 其他类型也可以同理设置,比如int类型设为123
        else if (property.PropertyType == typeof(int))
        {
            propertyData.Example = 123;
        }
        
        return propertyData;
    }
}
  1. 在Nancy的Bootstrapper里替换默认的构建器:
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
    base.ConfigureApplicationContainer(container);
    // 注册自定义的模型数据构建器
    container.Register<ISwaggerModelDataBuilder, CustomSwaggerModelDataBuilder>();
}

这样所有模型的属性都会按照你写的逻辑自动生成示例,不用一个个手动设置。

方法2:在MetadataModule里手动指定(单个模型生效)

如果只想给特定模型的属性加示例,直接在Metadata的模型定义里设置更灵活:

public class UserMetadataModule : MetadataModule<PathModule>
{
    public UserMetadataModule()
    {
        Describe<UserModel>("用户模型", model => model
            .WithProperty(x => x.Name, "用户名")
            // 这里直接给Name属性设置示例值
            .Example("张三")
            .WithProperty(x => x.Email, "邮箱地址")
            .Example("example@test.com")
            .WithProperty(x => x.Age, "年龄")
            .Example(25)
        );

        // 接口的Metadata定义...
        Get["/user"] = description => description
            .WithApiKeyAuthentication()
            .WithResponse(HttpStatusCode.OK, "成功返回用户列表", typeof(List<UserModel>));
    }
}

这样Swagger UI里的UserModel属性就会显示你指定的示例值,而不是默认的类型占位符了。

两种方法都试过,亲测有效,你可以根据需求选!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:07:43