Dynamically change MapPageRoute URL based on logged in user using C# and VB.Net in ASP.Net

mayankv83
 
on Sep 11, 2021 02:25 AM
Sample_809152.zip
621 Views

Hello,

I have created Asp.Net application. There i use routes.MapPageRoute so finally my application url is look like http://xyz.com/user/home

Now I client wants different admin user has different url like 

http://xyz.com/user1/home

http://xyz.com/user2/home

User1, User2...and so on, Its creat from admin sode. So admin can share same portal but url different for all the user.

So, Please suggest us how we can handel this kind of secinario? 

Please help us.

Thanks

Mayank

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Sep 13, 2021 12:19 AM

Hi mayankv83,

Check this example. Now please take its reference and correct your code.

HTML

Login

<asp:TextBox runat="server" ID="txtUserName" />
<asp:Button Text="Login" runat="server" OnClick="OnLogin" />

Home

User Name: <asp:Label ID="lblUser" runat="server" />

Code

Namespaces

C#

using System.Web.Routing;

VB.Net

Imports System.Web.Routing

Global.asax

C#

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
    }

    static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("Home", "{user}/home", "~/Home.aspx");
    }
}

VB.Net

Public Class Global_asax
    Inherits HttpApplication

    Sub Application_Start(sender As Object, e As EventArgs)
        RegisterRoutes(RouteTable.Routes)
    End Sub

    Private Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
        routes.MapPageRoute("Home", "{user}/home", "~/Home.aspx")
    End Sub
End Class

Login

C#

protected void OnLogin(object sender, EventArgs e)
{
    // Code to validate login.
    Session["User"] = txtUserName.Text.Trim();
    Response.Redirect(string.Format("{0}/home", Session["User"].ToString()));
}

VB.Net

Protected Sub OnLogin(ByVal sender As Object, ByVal e As EventArgs)
    Session("User") = txtUserName.Text.Trim()
    Response.Redirect(String.Format("{0}/home", Session("User").ToString()))
End Sub

Home

C#

protected void Page_Load(object sender, EventArgs e)
{
    // Validate user is login or not.
    if (Session["User"] != null)
    {
        lblUser.Text = Page.RouteData.Values["user"].ToString();
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Session("User") IsNot Nothing Then
        lblUser.Text = Page.RouteData.Values("user").ToString()
    End If
End Sub

Screenshot