c# - 如何实现类似SO的url重写

标签 c# .net asp.net-mvc

我需要在我的 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 参数定义路由,并在 Controller 方法中检查是否已提供该参数

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

关于c# - 如何实现类似SO的url重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30349412/

相关文章:

c# - Linq Take 不工作

c# - 带有 MySQL 和分布式事务的 TransactionScope

c# - 在属性名称前加上一些字符 - JSON 序列化

c# - 如何在不一直打开 Outlook 的情况下开发和测试 Outlook 加载项的一部分?

c# - Entity Framework Core 不保存相关数据

c# - 如何在 .NET 的基类静态方法中获取类类型?

javascript - angular.js 上的 ASP.NET 捆绑和缩小失败

c# - 创建数据库查询方法

c# - 如何在 MVC 应用程序中管理 CSS

asp.net - MVC 6 WebAPI 返回序列化的 HttpResponseMessage 而不是文件流