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

Ale*_*lex 12 .net c# asp.net-mvc

我需要在我的asp.net MVC网站上实现类似SO的功能.

例如,当用户转到https://stackoverflow.com/questions/xxxxxxxx时

加载后,主题行与网址连接,网址就像这样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
        );
Run Code Online (Sandbox Code Playgroud)

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

小智 9

这被称为slug路线.实现此目的的一种方法是使用可选slug参数定义路径,并在控制器方法中检查是否已提供参数

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

然后在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);
}
Run Code Online (Sandbox Code Playgroud)