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

如何在AddRazorPagesOptions中使用通配符配置页面路由?

统一配置Razor Pages的.html后缀路由

你提到的直接用options.Conventions.AddPageRoute("/*", "/{*.html}")的写法是行不通的,因为Razor Pages的路由约定不支持这种全局通配符的写法。不过我们可以通过自定义路由约定来实现批量给所有页面添加.html后缀的需求,下面给你两种可行的方案:

方案一:使用自定义PageRouteConvention(推荐)

我们可以创建一个自定义的约定类,实现IPageRouteModelConvention接口,遍历所有页面并自动添加带.html后缀的路由模板:

public class HtmlSuffixRouteConvention : IPageRouteModelConvention
{
    public void Apply(PageRouteModel model)
    {
        // 给每个页面的现有路由,额外添加一个带.html后缀的路由规则
        var selectorCount = model.Selectors.Count;
        for (var i = 0; i < selectorCount; i++)
        {
            var originalSelector = model.Selectors[i];
            model.Selectors.Add(new SelectorModel
            {
                AttributeRouteModel = new AttributeRouteModel
                {
                    Template = originalSelector.AttributeRouteModel.Template + ".html"
                }
            });
        }

        // 如果你只想保留带.html后缀的路由,不想保留原无后缀路由,可以把上面的添加逻辑改成替换:
        // model.Selectors.Clear();
        // model.Selectors.Add(new SelectorModel
        // {
        //     AttributeRouteModel = new AttributeRouteModel
        //     {
        //         Template = model.ViewEnginePath.TrimStart('/') + ".html"
        //     }
        // });
    }
}

然后在ConfigureServices里注册这个约定即可:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc()
        .AddRazorPagesOptions(options =>
        {
            options.Conventions.Add(new HtmlSuffixRouteConvention());
        });
}

方案二:批量遍历页面添加路由(适合简单场景)

如果你不想写自定义约定类,也可以通过遍历项目中的Razor页面文件,批量添加对应路由:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc()
        .AddRazorPagesOptions(options =>
        {
            // 遍历Pages文件夹下所有.cshtml页面
            var pageFiles = Directory.EnumerateFiles(
                Path.Combine(Directory.GetCurrentDirectory(), "Pages"),
                "*.cshtml",
                SearchOption.AllDirectories
            );

            foreach (var file in pageFiles)
            {
                // 把文件路径转换成页面路由路径(比如Pages/Index.cshtml → /Index)
                var relativePath = Path.GetRelativePath(Path.Combine(Directory.GetCurrentDirectory(), "Pages"), file);
                var pageRoute = "/" + Path.ChangeExtension(relativePath, null).Replace(Path.DirectorySeparatorChar, '/');
                
                // 添加带.html后缀的路由
                options.Conventions.AddPageRoute(pageRoute, $"{pageRoute.TrimStart('/')}.html");
            }
        });
}

额外说明

  • 方案一的自定义约定会自动处理所有页面(包括后续新增的页面),不需要手动更新,是更灵活、可维护的方式。
  • 如果有个别页面不需要.html后缀,可以在自定义约定的Apply方法里添加判断逻辑,排除特定页面(比如判断model.ViewEnginePath是否为某个路径)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:45:39