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

如何将自定义ValidationAttribute添加到Swagger文档并显示自定义说明

自定义验证属性Swagger展示实现方案

步骤1:扩展自定义验证属性(可选,也可以直接读取ErrorMessage)

你可以直接在自定义的HelloWorldAttribute中预留规则说明字段,方便后续Swagger读取:

public class HelloWorldAttribute : ValidationAttribute
{
    // 自定义验证规则描述,可根据需求调整内容
    public string RuleDescription { get; set; } = "字段值需满足HelloWorld验证规则";

    // 原有验证逻辑保留
    public override bool IsValid(object? value)
    {
        if (value is string input && input.Contains("HelloWorld"))
        {
            return true;
        }
        ErrorMessage = "字段必须包含HelloWorld字符";
        return false;
    }
}

步骤2:实现自定义SchemaFilter

实现ISchemaFilter接口,在Schema生成阶段读取自定义验证特性的信息,写入到OpenAPI Schema的描述中:

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;

public class CustomValidationRuleFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        // 只处理属性级别的特性标记
        if (context.MemberInfo is not PropertyInfo propertyInfo)
        {
            return;
        }

        // 读取属性上的HelloWorldAttribute
        var helloWorldAttr = propertyInfo.GetCustomAttribute<HelloWorldAttribute>();
        if (helloWorldAttr != null)
        {
            // 拼接规则描述到字段说明中
            var ruleTip = $"<br/>*自定义验证规则*:{helloWorldAttr.RuleDescription}";
            schema.Description = string.IsNullOrEmpty(schema.Description) 
                ? ruleTip.TrimStart('<','b','r','/','>') 
                : schema.Description + ruleTip;
        }

        // 后续新增其他自定义验证属性时,只需在此处扩展对应读取逻辑即可
    }
}

步骤3:注册SchemaFilter到Swagger配置中

找到项目Swagger注册的位置,添加Filter注册即可:

.NET 6+ 顶层语句(Program.cs)

var builder = WebApplication.CreateBuilder(args);

// 其他服务注册逻辑保留
builder.Services.AddSwaggerGen(options =>
{
    // 原有Swagger配置(比如Xml注释加载、标题版本设置等)保留
    options.SchemaFilter<CustomValidationRuleFilter>();
});

.NET 5及更早版本(Startup.cs ConfigureServices)

public void ConfigureServices(IServiceCollection services)
{
    // 其他服务注册逻辑保留
    services.AddSwaggerGen(options =>
    {
        // 原有Swagger配置保留
        options.SchemaFilter<CustomValidationRuleFilter>();
    });
}

补充说明

如果需要实现类似[Required]的星号标记,或者将规则写入到Schema的验证约束字段中,只需在Apply方法中修改schema对应的属性即可,比如给必填字段设置schema.Required = true。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:06:00