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

如何在Swagger UI中显示API参数的正则表达式规则

问题描述

我正在创建一个带HTTP端点的API,为参数myDateInput设置了正则表达式限制,用默认的WeatherForecastController做了简化示例:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;

namespace SplunkStatRelayService.Web.Controllers;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet(Name = "GetWeatherForecast")]
    public WeatherForecast Get(
        [FromQuery, RegularExpression(@"^(\\d\\d\\d\\d-\\d\\d-\\d\\d)"), Description("myDateInput must match the pattern")]
        string myDateInput)
    {
        return new WeatherForecast
        {
            Date = DateOnly.Parse(myDateInput),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = myDateInput,
        };
    }
}

正则规则可正常生效,输入不符合要求时会返回预期的400错误响应:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-8f9e4856bc5bfe091965e0404d28f9e9-8791bdf5988a2ec2-00",
    "errors": {
        "myDateInput": ["The field myDateInput must match the regular expression '^(\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\d)'."]
    }
}

但Swagger UI仅显示myDateInput为字符串类型,用户需触发错误才能知晓规则,且代码中的Description未显示。我曾尝试在services.AddSwaggerGen中添加EnableAnnotations但无变化,参考相关问题时提到了swagger.json文件,但我的项目中没有该文件。请问如何让Swagger UI显示正则规则和描述?是否需要手动创建swagger.json?

解决方案

关于swagger.json

不需要手动创建swagger.json,它是Swagger在项目运行时自动生成的,访问API的/swagger/v1/swagger.json路径即可查看生成的文档内容。

让Swagger UI显示正则规则和描述的步骤:

  1. 安装依赖NuGet包
    除基础的Swashbuckle.AspNetCore包外,还需安装Swashbuckle.AspNetCore.Annotations,这是启用Swagger注解支持的必要依赖。

  2. 正确配置Swagger生成器
    在Program.cs(或Startup.cs)的services.AddSwaggerGen配置中,启用注解并开启数据注解支持:

    builder.Services.AddSwaggerGen(c =>
    {
        c.EnableAnnotations();
        // 确保参数的验证规则能被Swagger正确渲染
        c.UseAllOfToExtendReferenceSchemas();
        // 可选:启用XML注释支持,需在项目属性中开启XML文档文件生成
        c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml"));
    });
    
  3. 替换描述注解
    原代码中的[Description]属于System.ComponentModel,Swagger默认不识别。改用Swashbuckle.AspNetCore.Annotations中的[SwaggerParameter]设置参数描述,同时优化正则表达式避免多余转义:

    [FromQuery, 
     RegularExpression(@"^\d{4}-\d{2}-\d{2}$"), 
     SwaggerParameter("myDateInput必须匹配YYYY-MM-DD格式的日期", Required = true)]
    string myDateInput
    
  4. 重启项目验证
    完成配置后重启API项目,打开Swagger UI即可看到:

    • 参数myDateInput下方显示设置的描述文本
    • 正则规则会以格式约束的形式展示在参数说明中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 20:20:14