Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在缺少“的情况下添加路由”;行动“;在url({controller}/{id})中_C#_Asp.net_Asp.net Mvc_Url Routing_Asp.net Mvc 5 - Fatal编程技术网

C# 在缺少“的情况下添加路由”;行动“;在url({controller}/{id})中

C# 在缺少“的情况下添加路由”;行动“;在url({controller}/{id})中,c#,asp.net,asp.net-mvc,url-routing,asp.net-mvc-5,C#,Asp.net,Asp.net Mvc,Url Routing,Asp.net Mvc 5,如何在ASP.NETMVC5中设置{controller}/{id}路由。 我想要实现的是:如果没有定义{action},请使用id调用Index() 我试过这个,但没有成功: // Keep default routing routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", i

如何在ASP.NETMVC5中设置
{controller}/{id}
路由。 我想要实现的是:如果没有定义
{action}
,请使用
id
调用
Index()

我试过这个,但没有成功:

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

// Add own routing in case of missing "action"
routes.MapRoute(
    name: "Controller/Id",
    url: "{controller}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

在阅读了ameer的评论之后,很明显,路由并不像我所希望的那样“智能”,因此如果URL模式匹配一个路由,但没有找到这样的控制器/方法,它将不会“失败”到下一个路由命令,而是会引发异常

因此,我尝试了Simon的建议,在自定义路由中添加了约束,并颠倒了顺序,现在就可以了。但是,如果我想有其他类似于附件的映射,我必须逐个添加它们

工作代码:

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

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

我不认为您可以按此顺序重载这些路由,因为ID在第一个路由中是可选的,所以路由的解析是不明确的,将默认为第一个添加的路由。e、 g.它将以您想要输入的id作为第一个路由中的操作名称。如果你想这样做,你必须把第二条路线放在第一位。不过,在这种情况下,要使用默认路由,您必须指定所有三个参数。如果您添加了一些约束并颠倒了规则的顺序,它可能会按照您的意图工作,谢谢您。我尝试了西蒙的建议,结果成功了。