Jos*_*e3d 5 asp.net-mvc asp.net-mvc-3
我的路线定义为:
{theme}/{subtheme}/{urltitle}列出文章详细信息,我想让其他人(而不是开发人员)为特定文章创建永久链接的可能性,例如http://www.whateverdomain/article-about-cars/:
{theme}/{subtheme}/{urltitle}如果本文有永久链接,我如何处理要重写为永久链接的请求?
要实现这一目标,您需要做三件事:
首先,让我们从我们的文章需要的信息开始:
Article
-------
Id <---------
Title \
Slug |
Theme |
SubTheme |
|
|
Permalink Table |
--------------- |
PermalinkId |
Name |
Slug /
ArticleId ---------
Run Code Online (Sandbox Code Playgroud)
//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"}
);
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
最后一部分是创建/读取功能,供用户创建永久链接.请注意,从SEO的角度来看这是"不好的"(当多个链接解析到同一页面时会发生稀释),但您可能想要这样做(无论出于何种原因).
对于每种方法,请确保将301重定向(RedirectToAction发出此问题)发布到正确的"当前"URL.如果你不这样做,你将受到搜索神的惩罚.
更新固定链接操作以将您重定向到Show操作:
public ActionResult ShowByPermalink(string PermalinkName)
{
var article = ArticleRepository.GetBy(PermalinkName);
return RedirectToAction("Show", article);
}
Run Code Online (Sandbox Code Playgroud)
现在创建永久链接.这涉及将CR(of CRUD)添加到Permalink存储库,就像我们之前使用文章一样.
以下是一些警告:
{permalinkId}/{permalinkName},则必须具有逻辑以确保所有永久链接都是唯一的.IRouteConstraint)将在请求时检查用户是否正在得到有效的蛞蝓正确的方式.但是,这是更多的工作,并导致更多的数据库命中(除非你有一个很好的缓存机制,但这会导致其他潜在的问题){something}行为的其他路由,则永久链路路径应位于路径的底部,如:http://example.com/something.否则,当您不希望发生这种情况时,其他路线将会触及永久链接路线.如果您有适当的路线约束,请不要担心这一点.