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

如何将所有Razor页面列表存入全局变量以生成自动导航菜单

解决方案

1. 修复空引用错误

你遇到的空引用问题,核心原因是JSONTest.endpointStringTest未完成初始化。静态集合默认值为null,调用Add方法必然会抛出空引用异常。修改JSONTest类,提前初始化集合即可解决:

public static class JSONTest
{
    // 初始化空列表,避免null引用
    public static List<string> endpointStringTest = new List<string>();
}

2. 理解endpointDataSources的注入逻辑

IEnumerable<EndpointDataSource>是ASP.NET Core依赖注入(DI)系统提供的内置服务,只有在DI容器管理的类(比如PageModel、Controller、注册的服务类)中,通过构造函数注入才能获取有效实例——DI容器会在创建类实例时自动填充该依赖。普通方法不属于DI注入场景,自然无法拿到有效值。

3. 更优雅的实现方案(推荐)

用静态类存储端点列表并非最佳实践,建议封装成可注入的服务,方便在全站任何地方复用:

步骤1:创建端点服务类

public class EndpointCollectionService
{
    public List<string> RazorPageEndpoints { get; }

    public EndpointCollectionService(IEnumerable<EndpointDataSource> endpointDataSources)
    {
        RazorPageEndpoints = new List<string>();
        LoadRazorPageEndpoints(endpointDataSources);
    }

    private void LoadRazorPageEndpoints(IEnumerable<EndpointDataSource> sources)
    {
        var razorEndpoints = sources
            .SelectMany(source => source.Endpoints)
            .OfType<RouteEndpoint>()
            // 可筛选仅保留Razor Pages端点,排除API、静态文件等无关端点
            .Where(endpoint => endpoint.DisplayName.Contains("/Pages/"));

        foreach (var endpoint in razorEndpoints)
        {
            RazorPageEndpoints.Add(endpoint.DisplayName);
        }
    }
}

步骤2:注册服务

在Program.cs中把服务注册为单例(端点列表在应用启动后不会变化,单例模式足够):

builder.Services.AddSingleton<EndpointCollectionService>();

步骤3:在PageModel中使用服务

public class IndexModel : PageModel
{
    private readonly EndpointCollectionService _endpointService;

    public IndexModel(EndpointCollectionService endpointService)
    {
        _endpointService = endpointService;
    }

    public void OnGet()
    {
        // 直接使用服务中的端点列表
        var endpoints = _endpointService.RazorPageEndpoints;
        // 写入文件或数据库的逻辑示例
        File.WriteAllLines("endpoints.txt", endpoints);
    }
}

4. 提前生成端点列表(可选)

如果需要在应用启动时就生成端点列表,无需等到访问Index页面,可以在Program.cs中添加启动逻辑:

var app = builder.Build();

// 应用启动后获取服务并写入文件
using (var scope = app.Services.CreateScope())
{
    var endpointService = scope.ServiceProvider.GetRequiredService<EndpointCollectionService>();
    File.WriteAllText("endpoints.json", JsonSerializer.Serialize(endpointService.RazorPageEndpoints));
}

// 后续中间件配置...
app.Run();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:45:29