Guest Post - Exploring ASP.NET FriendlyURLs

In this Guest Blog, our ASP.net/IIS MVP, Brij Bhushan Mishra is elaborating FriendlyURLs which is one of the features of ASP.net.

Being an ASP.NET developer, you must have worked on ASP.NET Web Forms and ASP.NET MVC. One of the things in MVC, most of us like that is pretty and elegant URL. But this is not in the case of using ASP.NET web forms.

These URLs include crappy extensions like aspx. Many developers have written their custom URL writer or used some third party libraries to achieve it. And here we either end up paying some extra bucks for the third party library or writing custom URL writer which is itself painful task.

FriendlyURLs was introduced with ASP.NET 4.5 release 2 as a NUGET package and can be used with ASP.Net 4.0+.

Working with FriendlyURLs

To start working with the friendly URLs, we need to install it via NuGet in our project and require to add some code in various files and make the change. First let’s set up the environment.

Setting up FriendlyURLs in your application

To install using user interface, go to Tools -> Library Package Manager -> Manage NuGet Package for Solutions and search ‘FriendlyURLs’ and click on install as:

image

Once you have the NUGET package installed then we need to call a method RegisterRoutes from Application_Start method in Global.asax as

protected void Application_Start(object sender, EventArgs e)

{

           RouteConfig.RegisterRoutes(RouteTable.Routes);

}

Now our application is set up with friendly URL when we’ll run our application, the URL will not contain file extension. Let’s run and check it.

image

The above URL does not contain the extension aspx.

There are many other scenarios where we need to play with URL’s, let’s discuss how the FriendlyURLs works in those scenarios.

  1. Redirect to other pages – This works in the similar way as earlier. We can either use Response.Redirect or Server.Transfer or any other way to go to other page i.e.: Reposne.Redirect (“~\second.”)
  2. Query string – Query string also works in the similar way as earlier. Like we can have an URL i.e.: http://localhost:57353/Home/Product?Id=1001 and the query string can be read as Request.QueryString["Id"] as string; it can contain many query string variable as earlier.
  3. If we access a URL and there is no page available then what would take place? Say if we have URL like http://localhost:57353/Home/Products/NewProduct and there is no page available with the name NewProduct then it looks the next segment Products. If products.aspx available then it opens this page. Similarly if this is also not available and it would like to search Home.aspxand display. It does the same until it finds any page or throw an error if no match is found. There are some other useful method provided by this feature. Let’s discuss some of the key items briefly.

Other useful Methods

To use these features, make sure you have added namespace Microsoft.AspNet.FriendlyUrls in your aspx.cs page.

  • Request.GetFriendlyUrlFileVirtualPath() - This method is available with the request returns the virtual path of the requested page. Here in my application, Home.aspx is under folder personal. Let’s have a look, here the requested URL is http://localhost:53252/Personal/Home then

image

  • Request.GetFriendlyUrlFileExtension() - It returns the file extension of the friendly URL of the page. Keep in mind that this return the file extension of the URL, not the extension of asp.net files like .master.ascx etc. As here also the accessed URL is same as in above section and

image

  • Request.GetFriendlyUrlSegments() - This is another method that got added with the request and returns the URL segment in a list of strings. First let’s understand what is the URL segment?

URL segments here are the additional values in the URL that are not part of the path or the page. If I have an URL as http://localhost:53252/Personal/Home/Users/User/3; the path of the page is /Personal/Home.aspx. Rest are additional values that are passed with the URL and available as URL segments. Let’s see what does it return when we access it.

image

Here as we see that there are three values in URL segments. In the same way, we can pass multiple additional values through URL without using query string. And obviously, it makes URL pretty, cleaner and SEO friendly.

The above methods works only in case of the requested URL is of type of FriendlyUrl.

Leveraging some useful Classes

There are some classes that are very useful while working with this feature. Let’s us take FriendlyURL first.

Using FriendlyURL Class

This is a static class which is very useful in several scenarios such as:

  • FriendlyUrl.Href – This is another method that generates the friendly URL based on the parameters. This is a very useful methods and can be used at several scenarios in code behind and in aspx mark-up as well. The parameters are:
    • First parameter is virtual path of the page
    • And then as many parameters that will be used as URL segments as

image

So here we first pass the virtual path of the page and rest three parameters are passed as Url segments, we can pass as many as segments as we need.

  • FriendlyUrl.Resolve – This is a static method and used to resolve any URL into friendly URL. This does not check whether that URL exists or not and it does not has to do anything about the requested URL.
image

Here we can see that the URL returned by the method is a Friendly URL.

  • FriendlyUrl.Segments – This is static property of the FriendlyUrl class and returns the URL segments of the URL similar as Request.GetFriendlyUrlSegments().

image

Here we have just accessed this property and it returned the URL segments for that page. Even we did not require to pass any information about the page.

Using FriendlyUrlResolver

FriendlyUrlResolver is a class that provides another set of good features that can be used at various scenarios. To use it, first we need to create the instance of FriendlyUrlResolver. Here the constructor requires one parameter that is the extension of URL that need to take care while working on friendly URL: FriendlyUrlResolver friendlyUrl = new FriendlyUrlResolver(".aspx")

It provides many methods such as:

  • ConvertToFriendlyUrl – It takes the normal URL as parameter and return the friendly URL based on the extension provided while creating the FriendlyUrlResolver instance as

image

Here we have created the instance FriendlyUrlResolver with the parameter .aspx then we used ConvertToFriendlyUrl that returns the friendly URL. Here if we have provided some other extension while creating the instance then this method returns null so be careful while using it.

  • GetExtensions - This is another method which returns the list of extensions that is configured for that instance. This method takes a parameter which is type HTTPContextBase. But we need to keep in mind that HttpContext.Current is not of type HTTPContextBase. To get the instance this type we can do:

HttpContextWrapper wrapper = new HttpContextWrapper(HttpContext.Current);

HttpContextWrapper inherits from HTTPContextBase so we can get the extensions as

image

  • PreprocessRequest – This is a virtual method and should be override at derived classes. This method takes two parameters an instance of HTTPContextBase and a handler instance. It executes once friendly URL is resolved and before executing the handler.
Conclusion

In this article, we discussed about FriendlyUrls and its various other components. It can be used with ASP.NET 4.0+ and easily configurable with the solutions. It provides a rich API to handle various scenarios. FriendlyUrlResolver class provides us capability to extend this feature based on our requirement.

About Guest Blogging

South Asia MVP Award Program introduces Guest Posts by the MVPs from the region. These posts would help readers to be in touch with the recent trends in technology and be up-to-date with knowledge on Microsoft products.

Author

image