'Statically-defined routes for @page in ASP.NET Core Razor Pages v6

My ASP.NET Core 6 RazorPage has this:

@page "/foo/bar"

I want to define that statically, like so:

@page @MyConstants.Pages.Foo.Bar

But that doesn't work.

There are some existing questions about this, but none have working solutions - perhaps they are for older versions. I tried all the recommended approaches:

@page [Route(MyConstants.Pages.Foo.Bar)]

and

@page [Route(route)]
@functions { public const string route = MyConstants.Pages.Foo.Bar; }

and

@attribute [RazorCompiledItemMetadata("RouteTemplate", MyConstants.Pages.Foo.Bar)]

How can I do this for ASP.NET Core Razor Pages version 6? (Note: not Blazor, but RazorPages specifically, which apparently has subtle differences in this regard.)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source