如何实现URL重写类似SO [英] how to implement url rewriting similar to SO
问题描述
我需要实现这么喜欢我的asp.net MVC的网站的功能。
I need to implement SO like functionality on my asp.net MVC site.
例如,当用户转到<一个href="http://stackoverflow.com/questions/xxxxxxxx">http://stackoverflow.com/questions/xxxxxxxx
加载主题行后的值与URL和URL变成这样<一个href="http://stackoverflow.com/questions/xxxxxxxx/rails-sql-search-through-has-one-relationship">http://stackoverflow.com/questions/xxxxxxxx/rails-sql-search-through-has-one-relationship
after loading the subject line is concatenated with the url and url becomes like this http://stackoverflow.com/questions/xxxxxxxx/rails-sql-search-through-has-one-relationship
以上/导轨-SQL-搜索通有一关系部分添加到URL。
Above "/rails-sql-search-through-has-one-relationship " part is added to the url.
在web表单很简单,我可以只使用URL重写。但不知道如何做到这一点的MVC
In webforms it's simple, I could just use url rewriting. But not sure how to accomplish this in MVC
下面一行是从Global.asax文件
The following line is from Global.asax file
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Account", action = "LogOn", id = UrlParameter.Optional } // Parameter defaults
);
这是我需要连接字符串在我的数据库中,以便从那里获取。我怎样才能做到这一点?
the string that I need to concatenate is in my database so it fetches from there. How can I accomplish this?
推荐答案
这就是所谓的塞路线。实现这一点的一种方法是定义一个可选蛞蝓
参数的路由,并在控制器方法检查,如果该参数已经提供
This is called a slug route. One way to achieve this is to define a route with an optional slug
parameter, and in the controller method check if the parameter has been provided
routes.MapRoute(
name: "Question",
url: "Question/{id}/{slug}",
defaults: new { controller = "Question", action = "Details", slug = UrlParameter.Optional }
);
然后在 QuestionController
(假定一个id总是会提供)
Then in QuestionController
(assumes an id will always be provided)
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);
}
这篇关于如何实现URL重写类似SO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!