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

如何在.NET Core Web Api的Swagger中覆盖‘No parameters’默认描述?

该需求可实现,以下是两种常用的落地方案:

方案一:使用IOperationFilter定向/全局配置(推荐,无需修改前端资源,支持不同接口设置不同说明)

该方案通过在生成OpenAPI文档时给无参接口添加自定义参数说明,替换默认的「No parameters」提示,同时支持针对单个接口单独配置描述内容。

操作步骤

  1. 先自定义操作过滤器类
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;

public class NoParamDescriptionFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        // 获取接口上标注的自定义说明特性
        var noParamAttr = context.MethodInfo.GetCustomAttribute<NoParamCommentAttribute>();
        // 只给标注了特性/无参数的接口添加说明
        if (noParamAttr != null || (operation.Parameters == null || !operation.Parameters.Any()))
        {
            operation.Parameters ??= new List<OpenApiParameter>();
            operation.Parameters.Add(new OpenApiParameter
            {
                Name = "接口说明",
                In = ParameterLocation.Query,
                Required = false,
                // 优先取特性上的自定义内容,没有则用全局默认说明
                Description = noParamAttr?.Description ?? "当前接口无需传入参数,参数自动从请求上下文提取",
                Schema = new OpenApiSchema { Type = "string", Default = new Microsoft.OpenApi.Any.OpenApiString("无需传参") }
            });
        }
    }
}
  1. 自定义说明特性(如果需要给不同接口配置不同的说明)
[AttributeUsage(AttributeTargets.Method)]
public class NoParamCommentAttribute : Attribute
{
    public string Description { get; }
    public NoParamCommentAttribute(string description) => Description = description;
}
  1. 在Swagger配置中注册过滤器
    .NET 6+的Program.cs中添加如下配置:
builder.Services.AddSwaggerGen(opt =>
{
    // 原有Swagger配置保留
    opt.SwaggerDoc("v1", new OpenApiInfo { Title = "你的接口文档", Version = "v1" });
    // 注册自定义过滤器
    opt.OperationFilter<NoParamDescriptionFilter>();
});
  1. 针对需要自定义说明的接口标注特性即可
[HttpGet("user/info")]
[NoParamComment("接口返回当前登录用户信息,用户ID从身份鉴权上下文自动获取,无需手动传参")]
public IActionResult GetUserInfo()
{
    // 你的业务逻辑
    return Ok();
}
方案二:注入自定义JS全局统一替换(适合所有无参接口使用相同提示的场景)

如果所有无参接口的提示内容都一样,可以通过修改SwaggerUI渲染后的文本实现,无需修改后端逻辑。

操作步骤

  1. 确保项目已开启静态文件中间件,Program.cs中UseSwaggerUI之前要先加:
app.UseStaticFiles();
  1. 在项目wwwroot目录下新建custom-swagger.js文件,内容如下:
// 监听SwaggerUI渲染,替换所有No parameters文本
setInterval(() => {
  document.querySelectorAll('.opblock-parameters .no-parameters').forEach(item => {
    if(item.textContent.trim() === 'No parameters'){
      // 替换为你需要的自定义内容
      item.textContent = '当前接口无需传入参数,参数自动从请求上下文提取';
    }
  })
}, 300);
  1. 在SwaggerUI配置中注入自定义JS
app.UseSwaggerUI(opt =>
{
    opt.SwaggerEndpoint("/swagger/v1/swagger.json", "你的接口文档 v1");
    // 注入自定义JS
    opt.InjectJavascript("/custom-swagger.js");
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:06:04