AddRazorPagesOptions Conventions.AddPageRoute

时间:2018-04-07 16:40:06

标签: razor asp.net-core asp.net-core-2.0

我有这段代码:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc()
        .AddRazorPagesOptions(options => {
            options.Conventions.AddPageRoute("/Index", "Index.html");
            options.Conventions.AddPageRoute("/rt", "rt.html");
        });
}

是否有可能而不是写每一页,有这样一条野猫路线?

options.Conventions.AddPageRoute("/*", "/{*.html}");

1 个答案:

答案 0 :(得分:1)

没有内置方法可以添加此类通配符路由。但是,您可以使用简单的页面路由约定(IPageRouteModelConvention的实现)来实现它。这是一个工作样本:

public class HtmlExtensionPageRouteModelConvention : IPageRouteModelConvention
{
    public void Apply(PageRouteModel model)
    {
        var selectorCount = model.Selectors.Count;
        for (var i = 0; i < selectorCount; ++i)
        {
            var attributeRouteModel = model.Selectors[i].AttributeRouteModel;
            if (String.IsNullOrEmpty(attributeRouteModel.Template))
            {
                continue;
            }

            attributeRouteModel.SuppressLinkGeneration = true;
            model.Selectors.Add(new SelectorModel
            {
                AttributeRouteModel = new AttributeRouteModel
                {
                    Template = $"{attributeRouteModel.Template}.html",
                }
            });
        }
    }
}

配置:

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

Sample Project on GitHub