Search code examples
asp.net-coreurl-routingrazor-pages

How to route ASP .NET Razor Pages with dynamic value in path before page?


I am using ASP .NET Core, Version 7. On my web app, tenants will be assigned an ID.

I want all the URLs on the app to be of the form so that the tenant ID is in the URL right after the server address and before the path to the page: http://serveraddress//PageName

Right now, I am using a query parameter, so it looks like: https://localhost:7161/ReportIssue?TenantId=6ee0558e-f783-4d6d-8bf9-b439835b3ad8

I want it to look like this: https://localhost:7161/6ee0558e-f783-4d6d-8bf9-b439835b3ad8/ReportIssue

How do I do this?


Solution

  • I used custom routing. I added @page "~/{TenantId}/" to the top of the page, and then in the .cs file added string TenantId to the page methods for OnGet and OnPostAsync. The navigation controls in _layout were then broken, and the @Model.TenantId field seems to be populated only after the _layout controls are inserted. For now I am copying the layout controls into all the pages, unifying that can be tomorrow's problem. Also had to switch to using an href= instead of the asp-* attributes in the navigation anchor tags.