我试图使我的网站urls更友好的搜索引擎优化,所以我使用这种方法来改变路由。(虽然我不知道这种方法是最好的还是不-但这不是我的问题!)
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时,我希望当页面加载自动的url更改以完成一个url,并在url中添加段塞,就像第一个.。
编辑:我想要一些和stackoverflow.com urls完全一样的东西。这两个网址:
http://stackoverflow.com/questions/34615538/how-to-make-url-in-mvc-5-seo-friendly-and-consistent
http://stackoverflow.com/questions/34615538打开相同的页面,但是当我们使用第二个页面(您可以检查)时,url会自动转换为第一个页面。但我的urls不是这样翻译的。
发布于 2016-01-06 16:17:04
好的,这个问题是我自己解决的。
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");
}也许是肮脏的..。但是完美的工作..。
https://stackoverflow.com/questions/34615538
复制相似问题