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}.
- public string GenerateItemNameAsParam()
- {
- string phrase = string.Format("{0}-{1}", Id, Name);
- string str = GetByteArray(phrase).ToLower();
- str = Regex.Replace(str, @"[^a-z0-9\s-]", "");
- str = Regex.Replace(str, @"\s+", "-").Trim();
- str = str.Substring(0, str.Length <= 30 ? str.Length : 30).Trim();
- str = Regex.Replace(str, @"\s", "-");
- return str;
- }
-
- private string GetByteArray(string text)
- {
- byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(text);
- return System.Text.Encoding.ASCII.GetString(bytes);
- }
- We need to modify the actionlink to point to the SEO friendly URL.
- <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.
- public class GetSEOFriendlyRoute : Route
- {
- public GetSEOFriendlyRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler) : base(url, defaults, routeHandler)
- {
- }
-
- public override RouteData GetRouteData(HttpContextBase httpContext)
- {
- var routeData = base.GetRouteData(httpContext);
-
- if (routeData != null)
- {
- if (routeData.Values.ContainsKey("id"))
- routeData.Values["id"] = GetIdValue(routeData.Values["id"]);
- }
-
- return routeData;
- }
-
- private object GetIdValue(object id)
- {
- if (id != null)
- {
- string idValue = id.ToString();
-
- var regex = new Regex(@"^(?<id>\d+).*$");
- var match = regex.Match(idValue);
-
- if (match.Success)
- {
- return match.Groups["id"].Value;
- }
- }
-
- return id;
- }
- }
- We need to add a new route in route.config file also.
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.Add("ProductDetails", new GetSEOFriendlyRoute("Home/ProductDetails/{id}",
- new RouteValueDictionary(new { controller = "Home", action = "ProductDetails" }),
- new MvcRouteHandler()));
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
- }
Here, we have added a route which is SEO friendly.
Let’s debug the application and review the results.
You can see 2 sets of product details links.
First is default MVC URL. On the click of that link:
The URL is not self-explanatory.
Let’s click on the second link, which will generate a custom URL.
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.