【问题标题】:Implementing a StackOverflow type URL redirect实现 StackOverflow 类型的 URL 重定向
【发布时间】:2014-04-04 07:11:12
【问题描述】:

我想在我的网站上实现StackOverflow 类型的 URL 重定向。 例如

当您在浏览器中输入https://stackoverflow.com/questions/11227809/ 时,它会自动将您重定向到https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array

即使您输入废品值代替标题,例如https://stackoverflow.com/questions/11227809/askl;fl;aksf,它也会根据帖子编号11227809 将您重定向到正确的值。

这是哪种类型的重定向?那是301 我知道,但是如何使用 .Net MVC 来实现这一点?

我在这里看到了一个非 MVC 解决方案Here 但需要一个基于 MVC 的解决方案。 谢谢。


My Route:

routes.MapRoute("QuestionUrlDetermine", "{qId}/{questionTitle}", new { controller = "Home", action = "QuestionUrlDetermine", questionTitle = UrlParameter.Optional }, new { qId = @"^\d{1,3}$" });

Action:

public ActionResult QuestionUrlDetermine (int qId)
{
    …
        return new RedirectResult(string.Format("/{0}/{1}", qId, questionTitle));
}

【问题讨论】:

标签: .net asp.net-mvc asp.net-mvc-4 redirect


【解决方案1】:

这可以使用RedirectResult 轻松完成:

public ActionResult Question(int id)
{
    string title = GetFromDatabaseUsingQuestionId(id);
    return new RedirectResult(string.Format("/question/{0}/{1}", id, title));
}

【讨论】:

  • 这表示404 当路由未定义并且当我定义路由时它进入重定向循环,因为在RedirectResult 之后它会再次针对路由执行操作。
【解决方案2】:

您可以将最后一个参数设为可选,然后在打开问题的操作中检查它是否与问题的标题匹配。如果它们不匹配,您可以简单地返回 RedirectResultRedirectToRouteResult

【讨论】:

  • 这表示404 当路由未定义并且当我定义路由时它进入重定向循环,因为在RedirectResult 之后它会再次针对路由执行操作。我已经用代码更新了我的问题,请检查。
  • 你用public ActionResult QuestionUrlDetermine (int qId, string questionTitle)定义了另一个函数吗?没有RedirectResult 就可以解决问题
猜你喜欢
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 2018-07-30
  • 2022-09-27
  • 1970-01-01
相关资源
最近更新 更多