MVC 中路由开头的 Id

发布于 2024-10-18 14:16:47 字数 254 浏览 2 评论 0原文

我有一种情况,我希望在我的应用程序中有一个路由,以便应用程序的索引方法可以识别此 http://www.website.com/ID

以及 http://www .website.com/Controller/Action 也应该可以工作。

问题是,当我设置与第一个 URL 相对应的路由时,第二个 URL 的路由不起作用(即使我为此设置了单独的路由)。

请告诉我我在这里做错了什么......

I have a situation where I want a route in my application so that the application's index method can recognize this http://www.website.com/ID

and also, http://www.website.com/Controller/Action should also work.

The problem is that, when I set up the route corresponding to the first URL, the route for the second URL does not work (even if I set up a separate route for that).

Please tell me what am I doing wrong here...

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

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

发布评论

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

评论(2

且行且努力 2024-10-25 14:16:47

ID 值是否具有某些区别特征,可以让您区分它与控制器名称之间的区别?例如,它是数字吗?如果是这样,您可以对第一条路由设置约束,使其仅匹配 id。这将允许其他请求落入第二个(默认)路由。

routes.MapRoute(
    "IdRoute",
    "{id}",
    new { controller = "home", action = "get" },
    new { id = "\d+" } // match ids that consist of 1 or more digits
);

routes.MapRoute(
    "Default",
    new { controller = "home", action = "index", id = UrlParameter.Optional }
);

Does the ID value have some distinguishing characteristic that would allow you to tell the difference between it and a controller name? For example, is it numeric? If so, you can set up a constraint on the first route so that it only matches ids. This would allow other requests to fall through to the second (default) route.

routes.MapRoute(
    "IdRoute",
    "{id}",
    new { controller = "home", action = "get" },
    new { id = "\d+" } // match ids that consist of 1 or more digits
);

routes.MapRoute(
    "Default",
    new { controller = "home", action = "index", id = UrlParameter.Optional }
);
断桥再见 2024-10-25 14:16:47

以下内容应该有效:

routes.MapRoute(
    "DefaultWithID",
    "{id}",
    new { controller = "Home", action = "Index" }
);

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

假设:

public class HomeController : Controller
{
    public ActionResult Index(string id)
    {
        return View();
    }
}

/123/Home/Index/123 都可以正常工作。

The following should work:

routes.MapRoute(
    "DefaultWithID",
    "{id}",
    new { controller = "Home", action = "Index" }
);

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Assuming:

public class HomeController : Controller
{
    public ActionResult Index(string id)
    {
        return View();
    }
}

Both: /123 and /Home/Index/123 work fine.

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