gpt4 book ai didi

asp.net-mvc - 默认操作的可选 ID

转载 作者:行者123 更新时间:2023-12-03 04:34:06 25 4
gpt4 key购买 nike

我有一个只有这条路线的网站:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

这是 Controller :

public class ImageController : Controller
{
public ActionResult Image(int? id)
{
if (id == null)
{
// Do something
return View(model);
}
else
{
// Do something else
return View(model);
}
}
}

现在这是默认操作,因此我无需 ID 即可直接访问我的域来访问它。为了调用 id,通过/Image/Image/ID 就可以正常工作。然而我想要的是在没有图像/图像的情况下调用它(所以/ID)。现在这不起作用。

这是默认路由的限制还是有办法让它发挥作用?

谢谢

最佳答案

创建特定于此网址的新路由:

routes.MapRoute(
name: "Image Details",
url: "Image/{id}",
defaults: new { controller = "Image", action = "Image" },
constraints: new { id = @"\d+" });

确保在此之前注册上述路由:

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

否则它将不起作用,因为默认路由将优先。

这里我声明,如果 url 包含“/Image/1”,则执行 ImageController/Image 操作方法。

public ActionResult Image(int id) {//.....//}

该约束意味着 {id} 参数必须是数字(基于正则表达式 \d+),因此不需要 nullable int,除非您确实想要 nullable int,在这种情况下,请删除约束。

关于asp.net-mvc - 默认操作的可选 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26948361/

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