Asp.net mvc 默认操作的可选id

Asp.net mvc 默认操作的可选id,asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing,Asp.net Mvc,Asp.net Mvc 5,Asp.net Mvc Routing,我得到了一个只有这条路线的站点: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Image", action = "Image", id

我得到了一个只有这条路线的站点:

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 }
        );
}
这是控制器:

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可以很好地工作。但是我想要的是在没有Image/Image(so/id)的情况下调用它。现在不行了

这是默认路由的一个限制还是有办法让它工作


谢谢

为此url创建一个新路由:

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+
),因此不需要可为空的int,除非您确实需要可为空的int,在这种情况下,请删除该约束。

并在现有
控制器/action/id
路由之前注册此路由!建议用以下内容更新您的答案:)谢谢这让我找到了正确的方向。我最终选择了这条路线。MapRoute(“图像详细信息”、“{id}”、新的{controller=“Image”、action=“Image”});我从Image/{id}中删除了Image/。也不需要约束。@强烈建议使用该约束,甚至可能需要。否则,像
/Home
这样的请求将最终匹配新的仅映像路由,而不是匹配
controller=Home