Wednesday, November 17, 2010

Nice Urls - Slugs

By default ASP.NET MVC comes with urls like the following: /products/details/256. I find this already some kind of improvement over the normal web forms urls with aspx filename in the end but having numbers in the url is not really fashionable and SEO compatible. So while refactoring my app I thought that I will also make some fashionable and beautiful urls using so called slug. A slug is url compatible (no special characters, no spaces) string that is generated usually from the title of the item. So with slugs you can have url like /products/details/back-pack. It is not at all so hard to generate slugs. So you need an extra colums in the database table and on creation you generate the slug than you just need a GetBySlug instead of GetById and it is all working. If you are like me and have started out with ids and then change for slugs and want to keep also the "old" urls working the best is to have a GetByIdorSlug that tries to parse the third part of the url, and if it is an int it gets by id otherwise by slug, and that way old and new urls will work. :) Ok enough talking. I get to the point. Here is the code how to generate slug:
 public static string RemoveDiacritics(string stIn)
        {
            string stFormD = stIn.Normalize(NormalizationForm.FormD);
            StringBuilder sb = new StringBuilder();

            for (int ich = 0; ich < stFormD.Length; ich++)
            {
                UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
                if (uc != UnicodeCategory.NonSpacingMark)
                {
                    sb.Append(stFormD[ich]);
                }
            }

            return (sb.ToString().Normalize(NormalizationForm.FormC));
        }

        public static string CreateSlug(string stIn) { 

            string slug = stIn.ToLower();
            slug = RemoveDiacritics(slug);

             // Replace unwanted characters with space
             slug = Regex.Replace(slug, @"[^a-z0-9\s-]", " ");
             // Replace multple white spaces with single space
             slug = Regex.Replace(slug, @"\s+", " ").Trim();
             // Replace white space with -
             slug = slug.Replace(" ", "-");
 
             return slug;
        }

No comments:

Post a Comment