如何实现类似于SO的url重写 [英] how to implement url rewriting similar to SO

查看:31
本文介绍了如何实现类似于SO的url重写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的 asp.net MVC 站点上实现类似 SO 的功能.

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

例如当用户访问 https://stackoverflow.com/questions/xxxxxxxx

加载主题行后与 url 连接,url 变成这样 https://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 https://stackoverflow.com/questions/xxxxxxxx/rails-sql-search-through-has-one-relationship

上面的/rails-sql-search-through-has-one-relationship"部分被添加到url中.

Above "/rails-sql-search-through-has-one-relationship " part is added to the url.

在 webforms 中很简单,我可以只使用 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?

推荐答案

这称为 slug 路由.实现此目的的一种方法是使用可选的 slug 参数定义路由,并在控制器方法中检查是否已提供该参数

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);
}

这篇关于如何实现类似于SO的url重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆