In this tutorial, you will learn how to write some code that will get the friendly URL for any page created inside of an Episerver CMS-powered website. To accomplish this, you will learn all about the Url property and how to render it within a view. Episerver has two types of URLs, an internal Episerver identifier and a friendly URL based on the URLSegment property. You will not want to render the internal links within your views as they are not SEO friendly and look strange. If you are building a new Episerver project and you want to learn how to master URLs, read on 🔥🔥🔥

Add a Url property to a page

In order to render a link, you will need to add a property onto a page or block, so a content editor can add one inside of the CMS. This is done by defining a property of type Url as shown below:

Set the type of property to Url and decorate the p[property with the BackingType attribute, with the value set to PropertyUrl. Job done 💥

Displaying the UFriendly Url

The next task is to render the Url within a view. If you try to render the value of a Url property directly within a view, the rendered value will look like this:

How To Get The Friendly Url From Url Property in Episerver 9 1

These internal links are not created for SEO. This is why you will want to display the contents friendly Url instead. One way to do this is to use the Url.ContentUrl. You can access this extension method using the Url HTML helper within a Razor view, like so:

I personally do not like to write code like this as I think it breaks a fundamental aim of MVC. The main aim of using MVC is to separate your business logic from your presentation code. For me, having a helper in your view that takes in the internal Url and converts it to a friendly Url, reeks of adding business logic in the presentation layer. Instead, I think a better approach is to keep your concerns separated. You can achieve this by generating the friendly Url within the page controller and passing it into the view via a view model. As an added bonus when you follow this pattern, you can easily unit test this code as well. To do this you can use the UrlHelper:

You access UrlHelper via dependency injection. In this example, I use ServiceLocation to access the API. This makes the code snippet easy to read, however, this way of accessing an API is considered an anti-pattern. I recommend you use constructor injection to access the API in code. Just like the HTML helper, this API exposes ContentUrl. ContentUrl takes either ContentReference or a Urland will give you back the friendly Url.

You now know how to render a friendly Url within a view. The actual code is pretty easy which is why I advise that you do the conversion from internal to friendly URL in your controllers rather than your view. Happy Coding 🤘