Maz
Maz

Reputation: 59

ASP.NET Renaming web pages path

I am new to ASP.NET.

I have created a website with a nav bar which has a few links and I have published it on my hosting web server via the publish tool feature on visual studios. The project's files and folders is in my public_html folder on the web server

Everything is fine and working but I am wondering if it's possibe to change the path of the address.

Right now all my webforms are in a folder called "WebPages", which is in my project.

Webpages > HomePage.aspx
WebPages > Games.aspx
Webpages > Contact.aspx

To go to my Home page, a user must type:

www.mywebsite/WebPages/HomePage.aspx

He/She then can click on the game menu to go to Game.aspx.
For game web page, the web address will look like this:

www.mywebsite/WebPages/Game.aspx 

Now I am wondering if there is way to change the above website addresses so that the "WebPages" is taken out.

Reason why I made the WebPages folder is that I can keep all my webforms in one folder and all my CSS in another, to keep my project tidy.

Upvotes: 0

Views: 287

Answers (2)

Kawsar Hamid
Kawsar Hamid

Reputation: 514

By default, ASP.NET will always try to match the URL in a request to a file on disk. If no match is found, ASP.NET attempts to see if a match for the URL's pattern can be found in a RouteCollection object.

To add routes to a Web site, you add them to the static (Shared in Visual Basic) Routes property of the RouteTable class by using the RouteCollection.MapPageRoute method. You can do this in RouteConfig class in App_Start-

public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);

        routes.MapPageRoute(
            "webpagesGame",
            "Game/",
            "~/webpages/Game.aspx"
            );

        routes.MapPageRoute(
            "webpagesHome",
            "HomePage/",
            "~/webpages/HomePage.aspx"
            );
    }
}

Upvotes: 0

nelek
nelek

Reputation: 4312

Add to Your project Global.asax and then following code (it's in vb.net and target framework is .net 4.5) :

Imports System.Web.Routing

Private Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the application is started
        RegisterRoutes(RouteTable.Routes)
End Sub

Private Sub RegisterRoutes(routes As RouteCollection)
        routes.MapPageRoute("HomePage", "HomePage", "~/WebPages/HomePage.aspx")
        routes.MapPageRoute("Games", "Games", "~/WebPages/Games.aspx")
        routes.MapPageRoute("Contact", "Contact", "~/WebPages/Contact.aspx")
End Sub

Then user can type www.mywebsite.com/Contact for example and will be lead to Your www.mywebsite.com/WebPages/Contact.aspx.

I hope this example will help You.

Upvotes: 1

Related Questions