c# – 如何实现类似于SO的url重写
发布时间:2020-12-15 06:40:55 所属栏目:百科 来源:网络整理
导读:我需要在我的asp.net MVC网站上实现类似SO的功能. 例如,当用户去https://stackoverflow.com/questions/xxxxxxxx 加载后,主题行与url连接,url变成这样的https://stackoverflow.com/questions/xxxxxxxx/rails-sql-search-through-has-one-relationship 以上“/
我需要在我的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参数的路由,在控制器方法中检查是否提供了参数
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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |