定义不同HttpGet路由仍遇多端点匹配错误的原因与解决建议
错误原因及解决建议
错误原因
你遇到的AmbiguousMatchException是因为访问根路径/时,存在两个可匹配的GET端点:
- 你在
program.cs中直接定义的endpoints.MapGet("/", () => "This is the sample project"),明确处理GET /请求; - 你配置的传统路由
endpoints.MapControllerRoute("default", "api/{controller}/{action}/{id?}"),若项目存在默认的HomeController.Index方法,或是路由匹配逻辑误判,会被当作GET /的候选端点,最终导致路由歧义。
另外,你的CrmManagementController采用属性路由,endpoints.MapControllers()已足够处理所有API路由,额外添加的传统路由属于冗余配置,反而引发冲突。
解决建议
方式1:移除冗余的传统路由配置
由于控制器全部使用属性路由,MapControllers()可正确映射所有API路由,无需保留传统路由。修改program.cs的路由配置:
app.UseEndpoints(endpoints => { endpoints.MapControllers(); // 移除冗余的传统路由配置 endpoints.MapGet("/", () => "This is the sample project"); });
方式2:明确传统路由的默认值(如需保留)
若必须保留传统路由,需指定明确的默认值,避免其误匹配根路径/:
app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapControllerRoute( name: "default", pattern: "api/{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); // 指定默认控制器与动作 endpoints.MapGet("/", () => "This is the sample project"); });
注意:若项目中不存在HomeController和Index方法,该传统路由仍无法匹配任何请求,此时建议直接移除。
额外验证
确认项目中没有其他处理GET /请求的端点(比如默认生成的HomeController.Index方法),若有需修改或移除该方法的路由规则,避免冲突。
内容的提问来源于stack exchange,提问作者kumar425
相关产品推荐
相关产品推荐

