Create your own Short URLs

URLs for deeply nested pages can be difficult to read and even harder to remember, especially for new visitors to a website. When giving a presentation or participating in a technical conference, website owners tend to put shortened URLs on their slides so that the audience can write down the link on a piece of paper or navigate on their phone. Many URL shortening sites have caught on and you can find many examples with a quick search. But, these URLs are most often a string of random characters that do not have much meaning. What if we wanted them to be more memorable?

Creating Your own Short URLs

Lets say you have the following URL which is for a page that has information about the event at which you are presenting. www.mywebsite.com/events/northamerica/2017/july/exampleconference   

As you can see from the structure of the URL, the page for this conference is nested within some hierarchy that is related to the organization of the site. Yet, this URL may be difficult for someone who is unfamiliar with the organization of the pages and it is long enough to copy that users may find it tedious and opt to not even visit the page at all.

The first thing you need to make your own short URLs is a table in your database. This table simply needs 2 columns: short name and full URL. Using a table is important because it gives you flexibility as an admin section can be added so that these links may be added, updated, or removed at a moment's notice.

Below is the controller code for this short URL action.

[Route("go/{shortName}")]
public ActionResult Go(string shortName)
{
      var page = Context.Urls.SingleOrDefault(u => u.ShortName == shortName);

      if (page != null)
           return Redirect(page.Url);
      else
      {
           return RedirectToAction("Index", "Home");
       }
}

As you may notice, I am using attribute routing to make these URLs clean as they will not require a query string. The action itself is very simple: first the database is queried and tries to match the short name provided to a short name in the URL table. If a match was found, the controller redirects to that page, otherwise it redirects to the homepage (a default behavior).

The end result of this work is that now I can make the following short URL mywebsite.com/go/examplecon redirect to the full URL from before!

Thanks for reading!

Comments

Popular posts from this blog

ASP.NET Identity Remember Me

IIS Express Client Certificates

ASP.NET MVC - How to enable/disable CaC/Client Certificate authentication per area or route.