gpt4 book ai didi

c# - asp.net MVC 4 中的动态 RouteConfig

转载 作者:太空宇宙 更新时间:2023-11-03 16:19:56 25 4
gpt4 key购买 nike

我知道我可以在我的 MVC 应用程序的 RouteConfig 中更改路由:

routes.MapRoute(name: "epage", url: "view/SpecificURL", defaults: new {
controller = "ePage",
action = "Index"
})

但我想知道如何重定向来自数据库的值。我的数据库中有一行有标题。因此,对于来自数据库的每个标题,我想重定向到一个特定的 url例如。

数据库中的标题可能是 "pink" 我希望将 www.mydomain.com/pink 重新路由到特定的 url。我希望它重定向到的 URL 也在数据库中。我看了很多关于这个的问题,但似乎找不到任何动态改变 url 路由的问题

最佳答案

您可以像这样设置路线:

routes.MapRoute(name: "Default",
url: "{id}",
defaults: new { controller = "Home", action = "Index" });

然后在你的 Controller 中(在我的例子中是 HomeController):

public ActionResult Index(string id)
{
ContentResult cr = new ContentResult();
// Do a DB lookup here to get the data you need from the database to generate the appropriate content.
cr.Content = id;
return cr;
}

此示例仅返回发送的字符串。所以现在如果我浏览到 http://localhost/mysite/pink 我会得到“粉红色”作为我的结果。您可以轻松地使用此方法查找您的自定义数据库以确定要返回的正确内容。

如果您现有的路由不允许您采用这条路由:),那么您始终可以在 RegisterRoutes 方法中执行 SQL 查询并从中填充路由表。

关于c# - asp.net MVC 4 中的动态 RouteConfig,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14370619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com