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

Viewed 147

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.)

1 Answers

Try adding @page:

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

The Route attribute works for .razor pages, but not .cshtml.

Related