如何在控制器中添加路线

发布于 2024-12-28 16:18:47 字数 389 浏览 0 评论 0原文

我想在将新对象提交到数据库后映射一条新路线。因此,例如,如果我输入名称为“Test”的对象,我希望立即有一条新路由来解析“Test.aspx”。

System.Web.Routing.RouteTable.Routes.MapRoute(obj.NameUrl, obj.NameUrl + extension, new { controller = "per", action = "Index", name = obj.NameUrl });

在控制器中尝试过,但它不起作用(没有错误,只是生命周期中的时间可能不正确?)。相同的代码适用于 Application_Start()

I'd like to map a new route after I commit a new object to db. So for example if i enter object with name "Test" I would like to have a new route immediately, to resolve "Test.aspx".

I tried

System.Web.Routing.RouteTable.Routes.MapRoute(obj.NameUrl, obj.NameUrl + extension, new { controller = "per", action = "Index", name = obj.NameUrl });

in controller but it does not work (no error, just probably not right time in life cycle?). Same code works in Application_Start()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

分开我的手 2025-01-04 16:18:47

您应该避免动态注册路由。 Application_Start 中的以下静态路由应该能够处理具有动态路由参数的场景:

routes.MapRoute(
    "page",
    "{name}.aspx",
    new { controller = "per", action = "index" },
    new { name = @"[a-z0-9]+" }
);

并且如果扩展也必须是动态的:

routes.MapRoute(
    "page",
    "{name}.{extension}",
    new { controller = "per", action = "index" },
    new { name = @"[a-z0-9]+", extension = @"[a-z]{3,4}" }
);

然后您可以使用 Index 操作来处理请求此路线:

public class PerController: Controller
{
    public ActionResult Index(string name, string extension) 
    {
        ...    
    }
}

如果您想生成此操作的链接:

@Html.RouteLink("go to foo", "page", new { name = "foo", extension = "aspx" })

You should avoid registering routes dynamically. The following static route in your Application_Start should be able to handle your scenario of having dynamic route parameters:

routes.MapRoute(
    "page",
    "{name}.aspx",
    new { controller = "per", action = "index" },
    new { name = @"[a-z0-9]+" }
);

and if the extension has to be dynamic as well:

routes.MapRoute(
    "page",
    "{name}.{extension}",
    new { controller = "per", action = "index" },
    new { name = @"[a-z0-9]+", extension = @"[a-z]{3,4}" }
);

and then you could have the Index action to handle requests to this route:

public class PerController: Controller
{
    public ActionResult Index(string name, string extension) 
    {
        ...    
    }
}

and if you want to generate a link to this action:

@Html.RouteLink("go to foo", "page", new { name = "foo", extension = "aspx" })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文