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

ApiExplorerSettings(IgnoreApi=true)无法隐藏路由,是Bug还是特性?

问题解答

这不是Bug,是ASP.NET Core Minimal API的特性设计。

在Minimal API里,直接把[ApiExplorerSettings(IgnoreApi=true)]贴在路由的委托参数上是没用的——这个特性得加到端点元数据里,ApiExplorer才会识别。

给你两种正确的隐藏方式:

方法一:用WithMetadata注入特性

通过WithMetadata方法把ApiExplorerSettingsAttribute添加到端点的元数据集合中:

app.MapPost("/login", async (string returnUrl, HttpContext context, [FromServices] SignInManager<LiteDbUser> signInManager) =>
{
    var form = context.Request.Form;
    var result = await signInManager.PasswordSignInAsync(form["username"], form["password"], false, false);
    return result.Succeeded ? Results.Redirect(returnUrl ?? "/health") : Results.Redirect("/login");
}).WithMetadata(new ApiExplorerSettingsAttribute { IgnoreApi = true });

app.MapGet("/logout", async ([FromServices] SignInManager<LiteDbUser> signInManager) =>
{
    await signInManager.SignOutAsync();
    return Results.Redirect("/login");
}).WithMetadata(new ApiExplorerSettingsAttribute { IgnoreApi = true });

方法二:用ExcludeFromDescription简化操作

ASP.NET Core 6及以上版本提供了更省事的ExcludeFromDescription扩展方法,直接调用就能隐藏端点:

app.MapPost("/login", async (string returnUrl, HttpContext context, [FromServices] SignInManager<LiteDbUser> signInManager) =>
{
    var form = context.Request.Form;
    var result = await signInManager.PasswordSignInAsync(form["username"], form["password"], false, false);
    return result.Succeeded ? Results.Redirect(returnUrl ?? "/health") : Results.Redirect("/login");
}).ExcludeFromDescription();

app.MapGet("/logout", async ([FromServices] SignInManager<LiteDbUser> signInManager) =>
{
    await signInManager.SignOutAsync();
    return Results.Redirect("/login");
}).ExcludeFromDescription();

为啥原来的写法不行?

Minimal API的Map*方法返回的RouteHandlerBuilder负责管理端点的元数据,直接在委托上贴特性不会被ApiExplorer读取——它只会扫描端点元数据集合里的配置。所以必须通过上面两种方式把忽略设置加到元数据里,Swagger这类文档工具才会正确隐藏这些路由。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:53:26