Implementing SEO-friendly URLs turned out to be much easier than I expected - MVC routing already takes care of the "heavy lifting". The developer only needs to provide a function that returnes the "friendly urls" from strings (product names, blog titles etc.) and to update action links.
1. Routing. A new route needs to be added. It has to be added above the default route so that MVC framework attempted to match it first. The seofriendly parameter can be pretty much anything that will satisfy valid url requirements.
routes.MapRoute(
name: \"SEOFriendly\",
url: \"{controller}/{action}/{id}/{seofriendly}\",
defaults: new { controller = \"Home\", action = \"Index\", id = UrlParameter.Optional, seofriendly = \"\" }
);
2. Creating friendly urls. Here is an example I found on the web and added it "as is".
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;
}
3. Making use of the friendly url. Just adding an extra parameter to the object.
Before:
<div class=\"display-button\">@Html.ActionLink(\"Edit\", \"Edit\", new { id=item.PostID }) </div>
<div class=\"display-button\">@Html.ActionLink(\"Details\", \"Details\", new { id = item.PostID }) </div>
<div class=\"display-button\">@Html.ActionLink(\"Delete\", \"Delete\", new { id = item.PostID }) </div>
After:
<div class=\"display-button\">@Html.ActionLink(\"Edit\", \"Edit\", new { id=item.PostID, seofriendly = item.Title.ToSeoUrl() }) </div>
<div class=\"display-button\">@Html.ActionLink(\"Details\", \"Details\", new { id = item.PostID, seofriendly = item.Title.ToSeoUrl() }) </div>
<div class=\"display-button\">@Html.ActionLink(\"Delete\", \"Delete\", new { id = item.PostID, seofriendly = item.Title.ToSeoUrl() }) </div>
References:
SEO-Friendly URLs in ASP.Net MVC 3How can I create a friendly URL in ASP.NET MVC?
by Evgeny. Also posted on my website
1 comment:
It gives complete details about the urls.It is very interesting and informative information about the urls. Seo Company Bangalore
Post a Comment