Home > Back-end >  Creating a dynamic route
Creating a dynamic route

Time:11-29

I am trying to create dynamic routes using ASP.Net Core and Razor Pages. Basically, I have two razor pages. One is called Pages/Home.cshtml and another is called Pages/Calendar.cshtml. Each user that logs in has their own username. So let's say I have two users in my database, Sam and Jessica and let's say Sam is logged in and goes to http://www.example.com/Sam, then it should render Pages/Home.cshtml. If Sam is logged in and goes to http://www.example.com/Sam/Calendar, then it should render Pages/Calendar.cshtml. If Jessica is logged in and she goes to http://www.example/com/Jessica, then it should render Pages/Home.cshtml.

So basically, ASP.Net Core should look at the URL and compare the username with what's in the database. If the signed in user's username matches the URL, then it should render their home page. If their username does not match the URL then it should continue down the routing pipeline. I don't need help with the database stuff or anything like that. I only need assistance on how to set up the routing.

If all this sounds confusing, then just think of Facebook. It should work exactly like Facebook. If you go to http://www.facebook.com/<your.user.name>, then it brings up your time line. If you go to http://www.facebook.com/<your.user.name>/friends, then it brings up your friends list.

I am basically trying to duplicate that same behavior that Facebook has in ASP.Net Core and Razor Pages. Can someone please provide a simple example or point me to an example? I feel like the way to do this is to use some custom middleware or a custom route attribute, but I am not sure.

CodePudding user response:

You can do something like this. In the Program.cs/startup.cs modify the AddRazorPages like this.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages(options =>
{
    options.Conventions.AddPageRoute("/Index", "{user}");
    options.Conventions.AddPageRoute("/Calendar", "{user}/calendar");
});

var app = builder.Build();

Now when you access a URL like https://localhost:7131/sam/calendar you will get the calendar page. You can access the user variable like this - @RouteData.Values["user"]

And on the calendar page, you can do something like this.

public class CalendarModel : PageModel
{
    public void OnGet()
    {
        var user = RouteData.Values["user"];
        //Query the calendar information from Database.
        //If empty redirect the user to the home page or something.
    }
}

You can find more details about this here - Razor Pages route and app conventions in ASP.NET Core

  • Related