我在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>
为了更好地说明为什么这对我的网络应用程序很重要,请想象一下你会在stackoverflow.com上看到的长网址。
https://stackoverflow.com/questions/anchortaghelper-asp-page-to-use-lowercase
-- VS --
https://stackoverflow.com/Questions/Anchortaghelper-asp-page-to-use-lowercase
任何帮助,将不胜感激!
我看过这些其他参考文献,但没有运气:
将生成目标链接的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;
}
将以下内容添加到ConfigureServices
中的Startup.cs
方法中。它可以在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;
});