SEO-Friendly URLs in ASP.Net MVC 3

One of the most important things for a modern day website is for it to be easily found. If nobody can find your website, then it isn’t very useful. Google will usually rank a site higher with a URL like http://www.yourdomain.com/products/3/aniseed-syrup compared to http://www.yourdomain.com/products/3. In addition to being ranked higher by search engines, it is a lot easier for humans to remember as well. I am going to show you an easy way to create these SEO-style routes for your ASP.net MVC 3 applications.

1. Create a new project.

2. Create ADO.NET Entity Data Model and named NorthwindModel (I use Nortwind database for this tutorial)

3. Create a new controller and named ProductController.

4. Next we need to do in order to get this to work is create a route that will match this pattern. To do this you add new router in RegisterRouter method

routes.MapRoute(
                "NamedProduct",
                "product/{id}/{name}",
                new { controller = "Product", action = "Details", name = UrlParameter.Optional },
                new { id = @"^\d+$" }
            );

Note: you add new this router on above default router.

5. Create a new folder named Helpers in project so create a new class named StringHelper in Helpers folder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

namespace MvcApplications.RewriteURL.Helpers
{
    public static class StringHelpers
    {
        public static string ToSeoUrl(this string url)
        {
            // make the url lowercase
            string encodedUrl = (url ?? "").ToLower();

            // replace & with and
            encodedUrl = Regex.Replace(encodedUrl, @"\&+", "and");

            // remove characters
            encodedUrl = encodedUrl.Replace("'", "");

            // remove invalid characters
            encodedUrl = Regex.Replace(encodedUrl, @"[^a-z0-9]", "-");

            // remove duplicates
            encodedUrl = Regex.Replace(encodedUrl, @"-+", "-");

            // trim leading & trailing characters
            encodedUrl = encodedUrl.Trim('-');

            return encodedUrl;
        }
    }
}

6. Edit code of  ProductController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplications.RewriteURL.Models;
using System.Text.RegularExpressions;
using MvcApplications.RewriteURL.Helpers;

namespace MvcApplications.RewriteURL.Controllers
{
    public class ProductController : Controller
    {
        NorthwindEntities dbContex = new NorthwindEntities();

        //
        // GET: /Product/

        public ActionResult Index()
        {
            return View(dbContex.Products);
        }

        //
        // GET: /product/3
        public ActionResult Details(int id, string name)
        {
            Product product = dbContex.Products.FirstOrDefault(p => p.ProductID == id);

            // Redirect to proper name
            if (name != product.ProductName.ToRewireUrl())
                return RedirectToActionPermanent("Details", new { id = id, name = product.ProductName.ToRewireUrl() });

            return View(product);
        }

    }
}

7. Edit Index.cshtml file

@model IEnumerable
@using MvcApplications.RewriteURL.Helpers

..............

@Html.ActionLink("Details", "Details", new { id = item.ProductID, name= item.ProductName.ToRewireUrl() }) |

8. Build and run application

Advertisements
This entry was posted in ASP.NET MVC. Bookmark the permalink.

11 Responses to SEO-Friendly URLs in ASP.Net MVC 3

  1. mbowles201 says:

    Where did you get ToRewireUrl() from , don’t see it in your sample code.

  2. Great work I am going to update my site

  3. Sumesh says:

    What about Nuget package Microsoft.Aspnet.FriendlyUrls. It looks cleaner and easier to use.

  4. my result is : “/3?name=aniseed-syrup” not is “/3/aniseed-syrup” , plzzz helpi me.

  5. Ata S. says:

    You may also check out this package I’ve created: https://www.nuget.org/packages/LowercaseDashedRoute/
    And read the one-line configuration here: https://github.com/AtaS/lowercase-dashed-route

  6. Tùng Nguyễn Đức says:

    Thanks for your share.!
    But when i pass parameter “id=1, name = chính hãng” then URL show: “localhost:1234/loai-san-pham/1/ch-nh-h-ng”.
    How can i create url same: “localhost:1234/loai-san-pham/1/chính-hãng”?

    Thank you so much.!

  7. Minh says:

    Hello all,
    my result:
    http://localhost:11989/Stock/Detail/456?name=test-seo
    not is
    http://localhost:11989/Stock/Detail/456/test-seo
    source code:
    routes.MapRoute(
    “NameStock”,
    “Stock/Detail/{id}/{name}”,
    new { controller = “Stock”, action = “Detail”, name = UrlParameter.Optional },
    new { id = @”^\d+$” }
    );

    @Html.ActionLink(“Details”, “Detail”, new { id = 123, name = “test SEO”.ToSeoUrl() })

    please help me.
    Thanks so much.

  8. Sergey says:

    Good article but I have a question.
    In my database I use Guid (for example “a8e0bd52-a269-4322-8b23-276a353daf4f”) as ID. So my URL will look like that:
    http://localhost:12345/products/a8e0bd52-a269-4322-8b23-276a353daf4f/chef-antons-cajun-seasoning

    Is it well for search engines?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s