Clean SEO Friendly URLs With ASP.NET MVC 3
One of the major benefits of ASP.NET MVC is that it allows us truly dynamic URLs via its Routing system. We could declare a new Route like this:
routes.MapRoute(
"ArticleDetails", // Route name
"Article/{id}/{title}",
new { controller = "Article", action = "Details",title = "" },new { id = @"\d+" }
);
I wrote a simple method that encodes the URLs into a nice, safe, SEO friendly URL format:
public static class UrlEncoder
{
public static string ToFriendlyUrl(this UrlHelper helper, string title)
{
var url = title.Trim();
url = url.Replace(" ", " ").Replace(" - ", " ").Replace(" ", "-").Replace(",", "").Replace("...", "");
return url;
}
}
Here is some code on how you how could do this from your Controller Action:
public ViewResult Details(int id,string title)
{
Article article = db.Aritcles.Find(id);
routes.MapRoute(
"ArticleDetails", // Route name
"Article/{id}/{title}",
new { controller = "Article", action = "Details",title = "" },new { id = @"\d+" }
);
I wrote a simple method that encodes the URLs into a nice, safe, SEO friendly URL format:
public static class UrlEncoder
{
public static string ToFriendlyUrl(this UrlHelper helper, string title)
{
var url = title.Trim();
url = url.Replace(" ", " ").Replace(" - ", " ").Replace(" ", "-").Replace(",", "").Replace("...", "");
return url;
}
}
Here is some code on how you how could do this from your Controller Action:
public ViewResult Details(int id,string title)
{
Article article = db.Aritcles.Find(id);
string realTitle = UrlEncoder.ToFriendlyUrl(Url, article.Title).ToLower();
string urlTitle = (title ?? "").Trim().ToLower();
if (realTitle != urlTitle)
{
Response.Status = "301 Moved Permanently";
Response.StatusCode = 301;
Response.AddHeader("Location", "/Article/" + article.Id + "/" + realTitle);
Response.End();
}
return View(article);}
Here is some code on how you how could do this from your View:
<h2>Article List</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr><th>Title</th><th>Content</th><th>CreateTime</th><th>Author</th><th></th></tr>
@foreach (var item in Model) {
<tr>
<td>@Html.DisplayFor(modelItem => item.Title)</td>
<td>@Html.DisplayFor(modelItem => item.Content)</td>
<td>@Html.DisplayFor(modelItem => item.CreateTime)</td>
<td>@Html.DisplayFor(modelItem => item.Author)</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id, title = Url.ToFriendlyUrl(item.Title) }) |
@Html.ActionLink("Details", "Details", new { id=item.Id ,title=Url.ToFriendlyUrl(item.Title)}) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
Article List View:
Details View:
Download Source Code:http://www.kuaipan.cn/index.php?ac=file&oid=4876720616244129
转载于:https://www.cnblogs.com/lisknove/archive/2011/11/20/2256440.html