Search code examples
c#asp.net-corerazor-pagesasp.net-core-5.0

Dynamically routing using routes from a database


I have an ASP.Net Core 5.0 project. It uses Razor pages, not MVC. What I need to be able to do is have the routing engine look at the URL and if it doesn't match a page, it needs to go into the database and see if the name is in the database. If it is, then it needs to go to a generic page.

So my database has user names in it:

|--------------|
|     Joey     |
|   Samantha   |
|     Doc      |
|--------------|

As an example, if I go to https://www.example.com/Joey, it should actually load the /Pages/Users/Index.cshtml page and serve that up.

Same thing if I go to https://www.example.com/Doc, it should also load the /Pages/Users/Index.cshtml page.

I found a ton of examples on how to do this using classic ASP.Net and MVC, but I can't seem to find any good examples using .NET Core and Razor Pages.

My suspect that I need to add something to my startup file after services.AddRazorPages(); and I need to make some kind of custom routing service. Is good documentation available for this?


Solution

  • In your Index.cshtml page replace @page with @page "/{name?}". So you should have something like below:

    @page "/{name?}"
    @model MyApplicationNamespace.Pages.IndexModel
    

    After that change the Index.cshtml.cs like below:

    public IActionResult OnGet(string name)
    {
        // Here you check if name parameter given trough the URL an check with its existence in the database. if yes, then `return Page();`
        // Otherwise just redirect to the error page or something to let the user know what happened by using `return RedirectToPage("TheErrorPage");`
    }