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

Visual Studio 2022 Endpoints Explorer不显示扩展方法定义的Minimal API端点

问题描述

在Program.cs中直接编写API版本化端点注册代码时,Visual Studio 2023的Endpoints Explorer能正常显示对应端点:

var example = app.NewVersionedApi("example");

var group = example.MapGroup("v{version:apiVersion}")
                    .HasApiVersion(1);

example.MapGet("/", () =>
{
    return Results.Ok();
}); 

但将端点定义迁移到扩展方法后:

public static class StaticClass
{
    public static void AddEndpoints(this IVersionedEndpointRouteBuilder example)
    {
        var group = example.MapGroup("v{version:apiVersion}")
                     .HasApiVersion(1);

        example.MapGet("/", () =>
        {
            return Results.Ok();
        });
    }
}

Program.cs改为调用该扩展方法:

var example = app.NewVersionedApi("example");
example.AddEndpoints();

此时Endpoints Explorer不再显示该端点,但Swagger可正常展示。需要解决如何让端点重新在Endpoints Explorer中显示的问题。

解决方法

要让Visual Studio的Endpoints Explorer识别扩展方法中注册的API版本化端点,可按以下方式处理:

  • 添加程序集级端点发现器特性:在包含扩展方法的程序集(一般为当前项目)中,添加[assembly: EndpointDiscoverer(typeof(VersionedEndpointDiscoverer))]特性。可以将该特性放在项目的AssemblyInfo.cs文件中,或直接放在扩展方法类的文件顶部:
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.AspNetCore.Routing;

[assembly: EndpointDiscoverer(typeof(VersionedEndpointDiscoverer))]

public static class StaticClass
{
    public static void AddEndpoints(this IVersionedEndpointRouteBuilder example)
    {
        var group = example.MapGroup("v{version:apiVersion}")
                     .HasApiVersion(1);

        example.MapGet("/", () =>
        {
            return Results.Ok();
        });
    }
}

该特性会告知Visual Studio的端点发现器,使用API版本化专用的扫描逻辑识别扩展方法内的端点注册。

  • 检查端点注册逻辑:确保IVersionedEndpointRouteBuilder实例传递正确,端点注册代码无逻辑错误。如果需要将端点归入版本路由组,要把example.MapGet(...)改为group.MapGet(...),避免端点脱离版本组配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 15:35:20