使用 MVC4,我为博客帖子详细信息操作提供了以下路由,该操作是 SEO 友好的 URL:
public ActionResult Details(int id, string postName)
{
BlogPost blogPost = _blogService.GetBlogPostById(id);
string expectedName = blogPost.Title.ToSeoUrl();
string actualName = (postName ?? "").ToLower();
if (expectedName != actualName)
return RedirectToAction("Details", "Blog", new { id = blogPost.BlogPostId, postName = expectedName });
var vm = BuildBlogPostDetailViewModel(id);
return View(vm);
}
使用以下辅助方法构建 SEO 路由:
public static class Helper
{
public static string ToSeoUrl(this string url)
{
// ensure the the is 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;
}
}
这会产生这样的路线:
/Blog/Details/1?postName=user-group-2013
我想要实现的是以下路线:
/博客/详细信息/用户组-2013
关于如何实现和优化这一点的任何建议?
非常感谢