您的位置:首页 > 编程语言 > ASP

Clean SEO Friendly URLs With ASP.NET MVC 3

2011-11-06 10:47 281 查看
Source:

http://www.mikesdotnetting.com/Article/108/Handling-Legacy-URLs-with-ASP.NET-MVC <---

http://www.dominicpettifer.co.uk/Blog/34/asp-net-mvc-and-clean-seo-friendly-urls <----------

http://www.deliveron.com/blog/post/SEO-Friendly-Routes-with-ASPnet-MVC.aspx <----------

http://stackoverflow.com/questions/3620092/asp-net-mvc-routing-seo-friendly-url

http://weblogs.asp.net/scottgu/archive/2010/04/20/tip-trick-fix-common-seo-problems-using-the-url-rewrite-extension.aspx

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+" }

);[/b]

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;

}

}[/b]

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);[/b]

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);

}[/b]

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>[/b]

Article List View:



Details View:



Download Source Code:http://www.kuaipan.cn/index.php?ac=file&oid=4876720616244129
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: