问题描述
我试图让我的网站网址更加SEO友好,所以我用这种方法改变路由。(虽然我不知道这种方法是最好的方式与否 - 但这不是我的问题!)
I am trying to make my websites urls more SEO friendly, so I Used This approach to change routing.(although I dont know is this approach is Best Way or not - but this is not my Question!)
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操作:
This Is The "SingleQuestion" Action that Processes pages:
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));
}
当我使用这些网址时这很好用:
well this works fine when i use these Urls:
http://localhost:9408/soal/13/bla-bla-bla
和
and
http://localhost:9408/soal/13
当我使用第二个网址时,我希望当网页自动加载网址更改为Complete One和slug追加到网址,就像第一个。
我想要的东西与stackoverflow.com网址完全一样。这两个网址:
these urls direct to same pages But My only problem is this: when I use second url, I want when page loads automatically URL changes to Complete One and the slug append to the url, Like first One.
I want something exactly Like stackoverflow.com urls. these two urls:
http://stackoverflow.com/questions/34621154/centering-multiple-textviews-programmatically-on-android
http://stackoverflow.com/questions/34621154
打开同一页,但是当我们使用第二个(你可以检查)时,url会自动转换为第一个。但我的网址不会像这样翻译。
opens same page, But when we use second one(as you can examine ) url translates to first one automatically. but my urls does not translate like this.
推荐答案
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");
}
也许吧,它很脏......但完美无缺......
maybe it,s dirty... but perfectly works...
这篇关于如何在MVC 5 SEO友好和一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!