ASP.NET MVC 路由参数

发布于 2024-12-21 21:00:50 字数 161 浏览 2 评论 0原文

asp.net mvc 路由模式是

 {"some_parameter/{controller}/{action}/{id}"}

如果 some_parameter 可以为 null 或字符串为空,这是否是有效格式

asp.net mvc routing pattern is

 {"some_parameter/{controller}/{action}/{id}"}

Is this a valid format if some_parameter can be null or string empty

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

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

发布评论

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

评论(2

隱形的亼 2024-12-28 21:00:50

我相信您想要的是 {some_parameter}/{controller}/{action}/{id} (注意“some_parameter”周围的大括号),在这种情况下它不应该为 null 或空, 我认为。如果 some_parameter 为空,您认为您的最终 URL 会如何与路由匹配? “mysite.com//mycontroller/myaction/myid”?

路由引擎只匹配模式。如果您想同时处理 {some_parameter}/{controller}/{action}/{id}{controller}/{action}/{id},只需定义两条路线。

I believe that what you wanted is {some_parameter}/{controller}/{action}/{id} (notice curly brackets around "some_parameter") and in that case it shouldn't be null or empty, I think. How do you think your end URL might look like to match the route in case when some_parameter is empty? "mysite.com//mycontroller/myaction/myid"?

Routing engine just matches patterns. If you want to handle both {some_parameter}/{controller}/{action}/{id} and {controller}/{action}/{id}, just define both routes.

森林迷了鹿 2024-12-28 21:00:50

编辑

我刚刚重新排序了路线注册,以便它可以正常工作:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new {
        controller = "home",
        action = "index",
        id = UrlParameter.Optional }
);

routes.MapRoute(
    "Default", // Route name
    "{some_parameter}/{controller}/{action}/{id}", // URL with parameters
    new {
        some_parameter = UrlParameter.Optional,
        controller = "home",
        action = "index",
        id = UrlParameter.Optional
    }
);

它们应该按该顺序注册。另外,第二条路由需要 id 和 some_parameter 参数,否则它永远不会因为前面的路由而被命中。即使 some_parameter 和 id 参数设置为可选,但这永远不会发生,因为如果它为空,之前的路由会捕获它。

Edit

I've just reordered the route registration so that it would work:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new {
        controller = "home",
        action = "index",
        id = UrlParameter.Optional }
);

routes.MapRoute(
    "Default", // Route name
    "{some_parameter}/{controller}/{action}/{id}", // URL with parameters
    new {
        some_parameter = UrlParameter.Optional,
        controller = "home",
        action = "index",
        id = UrlParameter.Optional
    }
);

They should be registered in that order. Additionally the second route requires an id and some_parameter parameter otherwise it will never be hit because of the route before it. Even though the some_parameter and id parameters are set to optional, that would never happen because the route before would catch it if it was empty.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文