问题描述
这称为“条状路线”。实现此目的的一种方法是使用可选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);
}
解决方法
我需要在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。
在网络表单中,这很简单,我可以只使用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
);
我需要连接的字符串在我的数据库中,因此可以从那里获取。我该怎么做?