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

时间:2015-05-20 12:16:31

标签: c# .net 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”部分被添加到网址。

在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
        );

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

2 个答案:

答案 0 :(得分:9)

这被称为slug路线。实现此目的的一种方法是使用可选的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);
}

答案 1 :(得分:3)

您正在寻找自定义路线。仔细观察,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) })
相关问题