ASP.NET 核心 Razor 页面强制 Anchor Tag Helper(asp-页面)使用小写路由

ASP.NET Core RazorPages to force AnchorTagHelper (asp-page) to use lowercase routes

我在 ASP.NET Core v2.0 中使用 RazorPages,我想知道是否有人知道如何强制 AnchorTagHelper 使用小写字母?

例如,在我的 .cshtml 标记中,我会使用 asp-page 标签助手来获得以下锚标签:

<a asp-page="/contact-us">Contact Us</a>

我正在寻找的输出

// i want this 
<a href="/contact-us">Contact Us</a>

// i get this 
<a href="/Contact-us">Contact Us</a>

为了进一步说明为什么这对我的网络应用很重要,请想象一个长 url,就像您在 whosebug.com

中看到的那样
https://whosebug.com/questions/anchortaghelper-asp-page-to-use-lowercase

                       -- VS --

https://whosebug.com/Questions/Anchortaghelper-asp-page-to-use-lowercase

如有任何帮助,我们将不胜感激!


我查看了这些其他参考资料,但没有成功:

将生成目标 link 的 url 助手将使用为路由生成的元数据。对于剃刀页面,这使用确切的文件路径来标识路由。

从 ASP.NET Core 2.1 开始,您可能可以像使用 Route 属性的 MVC 路由一样调整路由。至少 it’s planned for the 2.1 release.

在那之前,您必须在 ConfigureServices 方法中为您的页面配置特定的路由:

services.AddMvc()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AddPageRoute("/ContactUs", "contact-us");
    });

这将使现有路线可供使用,因此如果您不希望这样,则需要替换此页面的路线选择器。没有内置的方法可以做到这一点,但是当你知道该怎么做时,做起来并不难。

为了避免代码重复并使一切变得更好,我们将创建一个 ReplacePageRoute 扩展方法,它基本上与上面 AddPageRoute 的用法相匹配:

services.AddMvc()
    .AddRazorPagesOptions(options => {
        options.Conventions.ReplacePageRoute("/Contact", "contact-us");
    });

该方法的实现直接受到 AddPageRoute:

的启发
public static PageConventionCollection ReplacePageRoute(this PageConventionCollection conventions, string pageName, string route)
{
    if (conventions == null)
        throw new ArgumentNullException(nameof(conventions));
    if (string.IsNullOrEmpty(pageName))
        throw new ArgumentNullException(nameof(pageName));
    if (route == null)
        throw new ArgumentNullException(nameof(route));

    conventions.AddPageRouteModelConvention(pageName, model =>
    {
        // clear all existing selectors
        model.Selectors.Clear();

        // add a single selector for the new route
        model.Selectors.Add(new SelectorModel
        {
            AttributeRouteModel = new AttributeRouteModel
            {
                Template = route,
            }
        });
    });

    return conventions;
}

将以下内容添加到 Startup.cs 中的 ConfigureServices 方法中。可以在services.AddMvc();

之前或之后添加
services.AddRouting(options =>
{
    options.LowercaseUrls = true;
});

现在是锚标签

<a asp-page="/Contact-Us">Contact Page</a>

和输出

<a href="/contact-us">Contact Page</a>

现在更容易了,只需将其添加到 Startup.cs 中的 ConfigureServices 方法即可。

 services.Configure<RouteOptions>(options =>
                {
                    options.LowercaseUrls = true;
                });