Click here to Skip to main content
15,883,705 members
Articles / Web Development / ASP.NET

FriendlyURL: A New and Exciting Feature of ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.20/5 (4 votes)
2 Jan 2013CPOL5 min read 29.1K   7   2
FriendlyURL as the name suggests gives a clean and SEO friendly URL.

This is going to be my last post of 2012. I am very happy that I am writing about a very exciting feature that comes with ASP.NET.

I am really excited to learn and write about this. I really hated the ugly URLs and the extensions of the page that were always visible when one opens the application until and unless you write your own custom URL processor. With ASP.NET 4.0, Routing was introduced, which provided the capability to ASP.NET to have easier, manageable and SEO friendly urls, I wrote a post on it. You can click below to have a look at it.

But that is a little tidy to write. And it looks like writing extra code that does not produces any business functionality.

FriendlyURL as the name suggests gives a clean and SEO friendly URL. Currently, it is available via NuGet and in pre release version.

So for this post, I have used my Visual Studio 2012 IDE. I created a new project as File-> New -> Website -> ASP.NET Empty Website.

Once the project gets created, I require to install the NuGet for my application. So go to Tools-> Library Package Manager-> Package Manager Console.

Package Manager Console

It opens a console, then type Install-Package Microsoft.AspNet.FriendlyUrls -Pre and press enter as:

FriendlyURL NugetInstallation

As you can see, I typed the command and it can be seen in the first red encircled area and press enter. It’ll install the NuGet and you can see the last red encircled area which shows FirendlyUrl is successfully added.

This can be used with two ASP.NET versions: ASP.NET 4.5 and ASP.NET 4.0.

Now you are ready to work with friendly URLs.

If you have read the Readme.text, it gives a clear idea how to start with. But I’ll take you through the steps. So let’s start.

Step 1

Add and create a Class name, preferably RouteConfig.cs (You can have any name. I used MyRouteConfig.cs) and make it static. Also add the namespace in the class Microsoft.AspNet.FriendlyUrls.

Step 2

Create a static function in the class preferably named as RegisterRoutes with a parameter of type RouteCollection and add a line routes.EnableFriendlyUrls() in the method as:

C#
public static class MyRouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.EnableFriendlyUrls();
    }
}

Step 3

Add Global.asax file and add the following line in Application_Start as:

C#
void Application_Start(object sender, EventArgs e)
  {
      MyRouteConfig.RegisterRoutes(RouteTable.Routes)
  }

Now you can start the development of your application. I have created two pages, First.aspx and Second.aspx in my solution.

That’s it. Now your code is ready to run.

First Page

If you see the circled area in the above picture, it does not contain page extension (aspx). So now the url looks pretty. As an end user, I don’t care about the page extension and even sometimes, it just irritates me.

Now if you want to redirect to another page, you can redirect by typing URL without page extension as:

C#
Response.Redirect("~\\Second");

There is one caveat here. You cannot have a folder and Page with the same name at the same level. If you have the name of a folder and the name of aspx page at the same level, you would not be able to access the page without extension. So please keep it in mind.

Now you must have a question in Querystring. What will happen with Querystring?

You don’t need to worry at all. QueryStrings will work as earlier. Let’s have a look to the URL http://localhost:57353/First?Id=1001, then you can read the QueryString as below similar to the earlier:

C#
string Id = Request.QueryString["Id"] as string;

Next point, if I have a URL say http://localhost:57353/First/Products/NewProduct and there is no page as NewProduct. What will happen. It’ll open First.aspx.

But, how does it work?

It starts from last segment (NewProduct) and will check if there is any NewProduct.aspx. If not, then it moves to the next segment and continues till it finds the exact aspx page.

Let’s explore more. Go to the server side of the page and include the namespace Microsoft.AspNet.FriendlyUrls. You’ll get a bunch of methods that will be very useful at certain times.

  • Request.GetFriendlyUrlSegments() – It returns a collections of string which represents the URL segments. So if I have a URL http://localhost:57353/First/Products/NewProduct and the page exists First.aspx, then it returns.

    URLSegments

    So you can see above, there are two segments and one can iterate through it. These url segments can be used to pass the values to a page via URL instead of QueryString. It also looks pretty.

  • Request.GetFriendlyUrlFileVirtualPath() – It returns the File virtual path. For the URL, discussed in the above example it will show as:

    File Virtual Path
    You can see it shows the Virtual path of the file.

  • Request.GetFriendlyUrlFileExtension() -It returns the extension of the file. For the above url, it will be shown as:

    File Extension
    As you can see, the extension of the page. As now with friendly url, the page extension is not shown. You can get the extension by the above method.

There are other important methods/features available that can be used to generate the URL, etc. I’ll discuss some of those here.

An available class FriendlyURL provides few static functions/properties that are very useful. Let’s see.

  • FriendlyUrl.Segments: Returns the segments of the current URL similar as returned by Request.GetFriendlyUrlSegments().
  • FriendlyUrl.Resolve: This can be used to resolve the FriendlyUrl.
  • FriendlyUrl.Href – It takes few parameters virtual path and list of url segments and generate the friendly URL out of it. And it is very useful while generating the URL in data binding and several other places. We can write:
    C#
    FriendlyUrl.Href("~/First", "Product", 1001);

    And what it will return:

    FriendlyURLgeneration

Hope you must have liked this new coming feature of ASP.NET. This will let you get rid of aspx extension in the URL. Frankly speaking, during the earlier days of my career, I used to see the extension to check if the website is developed in ASP.NET.

I find this feature as one of the most of the exciting features of ASP.NET. Hope all of you enjoy it and also like the post.

Enjoy and love ASP.NET. And a very Happy New Year to all.

Cheers!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Brij is a 3-times Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. More than 6 years of experience in IT field, currently serving a MNC as a Tech Lead/Architect.

He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.

He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website www.asp.net.

He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.

Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.


Visit his Blog: Code Wala

Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008

Comments and Discussions

 
Questionignore method not working Pin
k yabroudi1-Dec-13 1:35
k yabroudi1-Dec-13 1:35 
GeneralMy vote of 5 Pin
Anurag Gandhi7-Jan-13 0:09
professionalAnurag Gandhi7-Jan-13 0:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.