我需要在我的 asp.net MVC 站点上实现类似 SO 的功能。
例如,当用户转到 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
);
我需要连接的字符串在我的数据库中,所以它从那里获取。我怎样才能做到这一点?
最佳答案
这称为 slug 路由。实现此目的的一种方法是使用可选的 slug
参数定义路由,并在 Controller 方法中检查是否已提供该参数
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);
}
关于c# - 如何实现类似SO的url重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30349412/