如何实现URL重写类似SO重写、如何实现、类似、SO

由网友(栀梦)分享简介:我需要实现这么喜欢我的asp.net MVC的网站的功能。I need to implement SO like functionality on my asp.net MVC site.例如,当用户转到http://stackoverflow.com/questions/xxxxxxxx加载主​​题行后的值与U...

我需要实现这么喜欢我的asp.net MVC的网站的功能。

I need to implement SO like functionality on my asp.net MVC site.

例如,当用户转到http://stackoverflow.com/questions/xxxxxxxx

加载主​​题行后的值与URL和URL变成这样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);
}
阅读全文

相关推荐

最新文章