我试图让我的网站 url 对 SEO 更友好,所以我使用这种方法来更改路由。(虽然我不知道这种方法是否是最佳方法 - 但这不是我的问题!)
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "interface",
url: "soal/{id}/{slug}", /* "soal" is only decor */
defaults:new { controller = "ui", action = "singleQuestion",
slug = UrlParameter.Optional} /*I made "slug" optional because I don't need this part to retrieve conternt from database */
/* slug only explains content of the webpage*/
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
这是处理页面的“SingleQuestion”操作:
public ActionResult singleQuestion(int id, string slug)
/* "slug" parameter here does nothing. Action Does not use this.*/
{
var questions = BQcnt.Questions;
var showQuestion = questions.Find(id);
if (showQuestion != null)
{
var AnswerOfShowQuestion = BQcnt.Answers.Where(
i => i.QuestionID == showQuestion.QuestionID);
ViewBag.lastQuestion = showQuestion;
ViewBag.answer_of_show_question = AnswerOfShowQuestion;
}
return View(questions.OrderByDescending(x => x.QuestionID));
}
好吧,当我使用这些 Urls 时,它工作正常:
http://localhost:9408/soal/13/bla-bla-bla
和
http://localhost:9408/soal/13
这些网址指向相同的页面但我唯一的问题是: 当我使用第二个 url 时,我希望当页面自动加载时 URL 更改为 Complete One 并且 slug 附加到 url,就像第一个一样。
编辑:我想要一些完全像 stackoverflow.com url 的东西。 这两个网址:
http://stackoverflow.com/questions/34615538/how-to-make-url-in-mvc-5-seo-friendly-and-consistent
http://stackoverflow.com/questions/34615538
打开相同的页面,但是当我们使用第二个页面时(如您所见),url 会自动转换为第一个页面。但我的网址不是这样翻译的。
最佳答案
ok,问题自己解决
public ActionResult singleQuestion(int id, string slug)
{
var questions = BQcnt.Questions;
var showQuestion = questions.Find(id);
if (showQuestion != null)
{
var AnswerOfShowQuestion = BQcnt.Answers.Where(
i => i.QuestionID == showQuestion.QuestionID);
ViewBag.lastQuestion = showQuestion;
ViewBag.answer_of_show_question = AnswerOfShowQuestion;
if (slug != showQuestion.slug)
{
return RedirectToAction("singleQuestion", new { id = id, slug = showQuestion.slug });
}
else
{
return View(questions.OrderByDescending(x => x.QuestionID));
}
}
return RedirectToAction("Index");
}
也许它很脏......但完美地工作......
关于asp.net-mvc - 如何使 MVC 5 中的 URL SEO 友好且一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34615538/