我正在尝试让我的网站网址更加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
这些网址指向同一页但我唯一的问题是: 当我使用第二个网址时,我希望当网页自动加载网址更改为完整一个并且该网格附加到网址时,就像第一个网址一样。
编辑:我想要一些完全像stackoverflow.com网址的东西。 这两个网址:
http://stackoverflow.com/questions/34615538/how-to-make-url-in-mvc-5-seo-friendly-and-consistent
http://stackoverflow.com/questions/34615538
打开同一页,但是当我们使用第二个(你可以检查)时,url会自动转换为第一个。但我的网址并没有像这样翻译。
答案 0 :(得分:3)
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");
}
也许它,肮脏......但完美无缺......