繁体   English   中英

ASP.NET MVC 4中的动态RouteConfig

[英]Dynamic RouteConfig in asp.net MVC 4

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

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

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

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

您可以这样设置一条路线:

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

然后在您的控制器中(以我的情况为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 ,我的结果将是“ pink”。 您可以轻松地使用此方法,然后对自定义数据库进行查找,以确定要返回的正确内容。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM