• 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.aspx and 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

  • MVP Blog Posts - Enterprise & Business Solutions (23rd February - 1st March 2014)

    ServerSchemaPreopareTask execution failed on an unrecoverable error

    By Balasaheb Ilag published on 02-23-2014

    Unable to prepare Schema for Lync Server 2013 on Windows Sever 2012….(more)

     

    Exchange 2007 to 2013: Public Folder Migration Issue

    By Prabhat Nigam published on 02-23-2014

    This issue is specific to 2007. We are trying to migrate public folders after all the mailbox migration has completed….(more)

     

    CASE Expression Issue in Linked Server Query

    By Visakh Murukesan published on 02-24-2014

    So the scenario was this. I had a table in a remote SQL Server instance from which I wanted to retrieve some data from. For illustration let the table be named TestLS with columns….(more)

     

    Create Hierarchical Address Books in Office 365

    By Manu Philip published on 02-25-2014

    The hierarchical address book (HAB) is a feature in Microsoft Exchange Server 2013, Exchange Online (Office 365) and Microsoft Outlook that enables end users….(more)

     

    Troubleshooting Windows Azure authentication in PowerShell

    By Aman Dhally published on 02-26-2014

    Yesterday we imported the certificate to my machine and it was working well. But today when I tried to connect to my Azure account using PowerShell….(more)

     

    What is loose Truncation in Exchange 2013 Sp1 DAG

    By Satheshwaran Manoharan published on 02-27-2014

    Normally if one Database copy goes offline in one of the DAG Members, Logs are not Truncated in all the databases copies….(more)

     

    Throw Statement in SQL Server 2012

    By Suprotim Agarwal published on 03-01-2014

    In SQL Server 2012, Microsoft introduced the THROW statement to throw error/exception during the execution of T-SQL program which will transfer….(more)

  • MVP Blog Posts - Developer (23rd February - 1st March 2014)

    How to change #WindowsPhone 8 Lock Screen background?

    By Kunal Chowdhury published on 02-23-2014

    As a WPDev, you might want to provide your users an option to change the Lock Screen of their Windows Phone 8 device. It can be from a locally stored images within the app XAP….(more)

     

    Different Transforms in XAML and Windows Phone

    By Senthil Kumar published on 02-23-2014

    The RotateTransform lets the developers to rotate the points of the element around the original point. The value by which the element to be rotated….(more)

     

    Agile Testing with Visual Studio 2012

    By Gouri Sohoni published on 02-24-2014

    This article discusses Agile Testing principles, along with some challenges faced while implementing Agile principles and resolving them using the tools….(more)

     

    Attribute Routing in MVC and Web API - exploring the goodness

    By Abhimanyu Vatsa published on 03-01-2014

    In this post you will learn about attribute routing and its goodness in MVC and Web API. In the beginning I will show you what it is by comparing….(more)

  • MVP Blog Posts - Consumer (16th - 22nd February 2014)

    Reduce file size in PowerPoint presentations in few clicks

    By Dr. Nitin Paranjape published on 02-16-2014

    Presentations containing lot of photos or images tend to be very large in size. It makes them unmanageable….(more)

     

    PowerPoint 2013 on Touch: Shape Floatie

    By Geetesh Bajaj published on 02-17-2014

    Whenever you tap on an object in Word, Excel, or PowerPoint versions of Office 2013 while using a touch device such as the Microsoft Surface….(more)

     

    Quick and easy Gantt chart using Excel

    By Purnachandra Duggirala published on 02-18-2014

    Gantt charts are a very popular way to visually depict project plans. Today, let us learn how to use Excel to make quick & easy Project Plan….(more)

     

    How To Fix Low Volume Sound when Playing Movies in Windows 8.1

    By Soumitra Sengupta published on 02-18-2014

    I have set my volume to maximum but when playing movies the sound is too low. I have tried different media players….(more)

     

    Loop through all List-Boxes or Combo-boxes on userform

    By Ashish Koul published on 02-22-2014

    Macro to loop through all combo-boxes and list-boxes on user-form and set the row-source….(more)

  • MVP Blog Posts - Enterprise & Business Solutions (16th - 22nd February 2014)

    CustomActionGroup in SharePoint 2013

    By Devendra Velegandla published on 02-16-2014

    In this article you will learn how to develop custom action group in SharePoint 2013 using declarative approach with the help of Visual Studio….(more)

     

    How To Deploy Software Updates Using SCCM 2012 R2

    By Prajwal Desai published on 02-16-2014

    In this post we will look at the steps on how to deploy software updates using SCCM 2012 R2. Deploying the software updates for the computers is essential, the software updates are….(more)

     

    Powershell and GUI : Button element

    By Aman Dhally published on 02-18-2014

    One of the main component of any GUI application are buttons. Without Buttons, no GUI applications seems….(more)

     

    The Lync Server Audio/Video Authentication service on Local Computer started and then stopped

    By Balasaheb Ilag published on 02-18-2014

    The Lync Server Audio/Video Authentication service on Local Computer started and then stopped. Some services stop automatically if they are….(more)

     

    Proximity search feature in maplytics

    By Roohi Shaikh published on 02-18-2014

    Advanced Find an awesome tool in the hands of users to query CRM data by custom filters. So you could look up all leads in a particular country….(more)

     

    Data validation using TRY_CONVERT function

    By Madhivanan Jr published on 02-19-2014

    One of the new functions introduced in version 2012 is TRY_CONVERT which is very handy in validating data with respect to specific datatypes. In earlier versions you may need….(more)

     

    How to Quickly Share a folder using Outlook Web app in Exchange 2013

    By Satheshwaran Manoharan published on 02-20-2014

    Mailbox A – Want to Share a folder called “MySharedFolder”….(more)

     

    T-SQL Tips: Get Business Weeks For a Month

    By Visakh Murukesan published on 02-20-2014

    Recently in one of my reporting projects, we required generating a list of business weeks along with the start and end dates for a given month….(more)