如何实现类似于SO的url重写

本文关键字:SO url 重写 类似于 何实现 实现 | 更新日期: 2023-09-27 17:50:06

我需要实现像我的asp.net MVC网站的功能。

例如当用户访问https://stackoverflow.com/questions/xxxxxxxx

加载后,主题行与url连接,url变成如下https://stackoverflow.com/questions/xxxxxxxx/rails-sql-search-through-has-one-relationship

上面"/rails-sql-search-through-has-one-relationship "部分添加到url中。

在webforms中这很简单,我可以使用url重写。但不确定如何在MVC

中实现这一点

下面一行来自Global。asax文件

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Account", action = "LogOn", id = UrlParameter.Optional } // Parameter defaults
);

我需要连接的字符串在我的数据库中,所以它从那里获取。我怎样才能做到这一点呢?

如何实现类似于SO的url重写

这被称为鼻涕虫路由。实现此目的的一种方法是定义带有可选slug参数的路由,并在控制器方法中检查该参数是否已提供

routes.MapRoute(
    name: "Question",
    url: "Question/{id}/{slug}",
    defaults: new { controller = "Question", action = "Details", slug = UrlParameter.Optional }
);

然后在QuestionController中(假设总是提供id)

public ActionResult Details (int id, string slug)
{
    if (string.IsNullOrEmpty(slug))
    {
        // Look up the slug in the database based on the id, but for testing
        slug = "this-is-a-slug";
        return RedirectToAction("Details", new { id = id, slug = slug });
    }
    var model = db.Questions.Find(id);
    return View(model);
}

您正在寻找自定义路由。如果你仔细观察,SO并不关心URL的文本部分。所以:

 http://stackoverflow.com/questions/xxxxxxxx/rails-sql-search-through-has-one-relationship
 AND
 http://stackoverflow.com/questions/xxxxxxxx/

都可以。你可以很容易地这样做:

routes.MapRoute(
    "Question",
    "questions/{id}/{title}",
    new { controller = "Question", action = "Details" });

诀窍是在创建链接时在末尾添加"slug":

@Html.RouteLink(
    "Read more.",
    "Question",
    new { id = question.Id, title = Slugger.ToUrl(question.Title) })