【发布时间】:2011-10-25 17:51:38
【问题描述】:
我的路线定义为:
{theme}/{subtheme}/{urltitle} 用于列出文章详细信息,我想让其他人(不是开发人员)为特定文章创建永久链接,例如 http://www.whateverdomain/article-about-cars/:
问题
如果这篇文章有固定链接,我该如何处理对{theme}/{subtheme}/{urltitle} 的请求被重写为固定链接?
【问题讨论】:
我的路线定义为:
{theme}/{subtheme}/{urltitle} 用于列出文章详细信息,我想让其他人(不是开发人员)为特定文章创建永久链接,例如 http://www.whateverdomain/article-about-cars/:
如果这篇文章有固定链接,我该如何处理对{theme}/{subtheme}/{urltitle} 的请求被重写为固定链接?
【问题讨论】:
要实现这一点,您必须做三件事:
首先,让我们从我们的文章需要哪些信息开始:
Article
-------
Id <---------
Title \
Slug |
Theme |
SubTheme |
|
|
Permalink Table |
--------------- |
PermalinkId |
Name |
Slug /
ArticleId ---------
//normal route for article
routes.MapRoute("article",
"{theme}/{subtheme}/{slug}",
new {controller = "article", action = "show" }
);
//Permalink route for article
//You may want to create a custom route constraint for this, or place at bottom of routes
routes.MapRoute("permalinkArticleRoute",
"{PermaLinkName}",
new {controller = "article", action = "showbypermalink"}
);
public class ArticleController : Controller
{
public ArticleRepository ArticleRepository {get; set;} //DI'd or constructor injected
public ActionResult Show(Article article)
{
var article = ArticleRepository.GetBy(article.theme, article.subtheme, article.slug);
ArticleViewModel avm = new ArticleViewModel(article);
return View(avm);
}
public ActionResult ShowByPermalink(string PermalinkName)
{
var article = ArticleRepository.GetBy(PermalinkName);
ArticleViewModel avm = new ArticleViewModel(article);
return View(avm);
}
}
public class ArticleRepository
{
//Uses Linq-to-SQL. Can be adapted for any other ORM. The retrieval logic is the same
//It's the actual code that differs
public Article GetBy(string theme, string subtheme, string slug)
{
return (from a in db.Articles where
(a.Theme == theme && a.Subtheme == subtheme && a.Slug == slug)
select a).FirstOrDefault();
}
public Article GetBy(string permalinkName)
{
return (from a in db.Articles
join p in Permalink on permaLink.ArticleId equals a.Id
where p.permalinkName == permalinkName
select a;
}
}
最后一部分是供用户创建永久链接的创建/读取功能。请注意,从 SEO 的角度来看,这是“不好的”(当多个链接解析到同一页面时发生的稀释),但您可能想要这样做(无论出于何种原因)。
使用每种方法,请确保向正确的“当前”URL 发出 301 重定向(RedirectToAction 发出此问题)。否则,你将受到搜索之神的惩罚。
更新您的永久链接操作以将您重定向到Show 操作:
public ActionResult ShowByPermalink(string PermalinkName)
{
var article = ArticleRepository.GetBy(PermalinkName);
return RedirectToAction("Show", article);
}
现在创建永久链接。这涉及将CR(属于CRUD)添加到永久链接存储库,就像我们之前在文章中所做的那样。
这里有一些注意事项:
{permalinkId}/{permalinkName},则必须具有确保所有永久链接唯一的逻辑。 IRouteConstraint)将是一种在请求时检查用户是否获得有效 slug 权限的方法。但是,这需要更多的工作并导致更多的数据库命中(除非您有良好的缓存机制,但这会导致其他潜在问题){something} 行为,您的永久链接路由应该位于路由的底部,例如:http://example.com/something。否则,当您不希望发生这种情况时,其他路线将击中您的永久链接路线。如果您有良好的路线限制,请不要担心这一点。【讨论】:
RedirectToAction,它将重写用户浏览器中的Url(我在上面详细说明了这一点)。