SEO Friendly URL Using MVC

Introduction

As search engines are playing a major role in the number of visits to the site, it is definitely advisable to keep your site optimized to the search engines. There are multiple factors that impact the site to be properly search optimized. One of them is the URL for the site.

It’s better to have an URL which is human readable and easily understandable than an URL which is not.

Bad URL - http://localhost:42725/Home/ProductDetails/1

Good URL - http://localhost:42725/Home/ProductDetails/1-mac-book-pro

In the case of a good URL, the user will be able to get an idea of the page itself, unlike the bad one.

Let’s get started to create SEO (Search Engine Optimized) friendly URL using MVC.

Details

MVC is having Default route like “{controller}/{action}/{id}” where the “id” is normally a number which acts as a key for the record. But to ensure the URL to be SEO friendly we need to change the “id” to contain a name. There can be multiple records with the same name existing in the database. That creates an issue while using a name of a record as “id” or key.

Here, I will be using the name and id combination to get the uniqueness for the view.

How to modify the URL?

  • Let’s have a method which will create an URL with combination of {id}-{name}.
    1. public string GenerateItemNameAsParam()  
    2.        {  
    3.            string phrase = string.Format("{0}-{1}", Id, Name);// Creates in the specific pattern  
    4.            string str = GetByteArray(phrase).ToLower();  
    5.            str = Regex.Replace(str, @"[^a-z0-9\s-]""");// Remove invalid characters for param  
    6.            str = Regex.Replace(str, @"\s+""-").Trim(); // convert multiple spaces into one hyphens   
    7.            str = str.Substring(0, str.Length <= 30 ? str.Length : 30).Trim(); //Trim to max 30 char  
    8.            str = Regex.Replace(str, @"\s""-"); // Replaces spaces with hyphens     
    9.            return str;  
    10.        }  
    11.    
    12.        private string GetByteArray(string text)  
    13.        {  
    14.            byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(text);  
    15.            return System.Text.Encoding.ASCII.GetString(bytes);  
    16.        }  
  • We need to modify the actionlink to point to the SEO friendly URL.
    1. <a href="@Url.Action("ProductDetails", "Home", new { id = item.GenerateItemNameAsParam() })">@item.Name</a>  
    Here, you can observe that we are invoking the GenerateItemNameAsParam method as “id” to create the URL.
  • We need to update the route table to handle the request also. To ensure that I have added a new class.
    1. public class GetSEOFriendlyRoute : Route  
    2.     {  
    3.         public GetSEOFriendlyRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler) : base(url, defaults, routeHandler)  
    4.         {  
    5.         }  
    6.    
    7.         public override RouteData GetRouteData(HttpContextBase httpContext)  
    8.         {  
    9.             var routeData = base.GetRouteData(httpContext);  
    10.    
    11.             if (routeData != null)  
    12.             {  
    13.                 if (routeData.Values.ContainsKey("id"))  
    14.                     routeData.Values["id"] = GetIdValue(routeData.Values["id"]);  
    15.             }  
    16.    
    17.             return routeData;  
    18.         }  
    19.    
    20.         private object GetIdValue(object id)  
    21.         {  
    22.             if (id != null)  
    23.             {  
    24.                 string idValue = id.ToString();  
    25.    
    26.                 var regex = new Regex(@"^(?<id>\d+).*$");  
    27.                 var match = regex.Match(idValue);  
    28.    
    29.                 if (match.Success)  
    30.                 {  
    31.                     return match.Groups["id"].Value;  
    32.                 }  
    33.             }  
    34.    
    35.             return id;  
    36.         }  
    37.     }  
  • We need to add a new route in route.config file also.
    1. public static void RegisterRoutes(RouteCollection routes)  
    2. {  
    3.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
    4.    
    5.             routes.Add("ProductDetails"new GetSEOFriendlyRoute("Home/ProductDetails/{id}",  
    6.             new RouteValueDictionary(new { controller = "Home", action = "ProductDetails" }),  
    7.             new MvcRouteHandler()));  
    8.    
    9.             routes.MapRoute(  
    10.                name: "Default",  
    11.                url: "{controller}/{action}/{id}",  
    12.                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
    13.             );  
    14. }  

Here, we have added a route which is SEO friendly.

Let’s debug the application and review the results.

ASP.NET

 

You can see 2 sets of product details links.

First is default MVC URL. On the click of that link:

ASP.NET

 

The URL is not self-explanatory.

Let’s click on the second link, which will generate a custom URL.

ASP.NET

Here, the URL is self-explanatory.

It will increase the chances of appearing early in the search result over the previous URL.

Please let me know your feedback or suggestions.