如何在 MVC 5 SEO 中使 URL 友好且一致?

how to make URL in MVC 5 SEO Friendly and Consistent?

我正在努力使我的网站 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 时,我希望当页面自动加载时 URL 更改为完整一个并且 slug 附加到 url,就像第一个一样。

编辑:我想要一些完全像 whosebug.com urls 的东西。 这两个 urls:




打开相同的页面,但是当我们使用第二个页面时(如您所见) url 自动转换为第一个页面。但是我的 urls 不是这样翻译的。

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");
}

也许它很脏……但效果很好……