Skip to main content
 首页 » 编程设计

c#之ASP.NET MVC C# routes.MapRoute 不工作

2024年01月01日38落叶

我正在更改 ASP.NET、MVC、C# 应用程序,但 routes.MapRoute 条目未按预期工作。在我的 Global.asax.cs 文件中,我有以下两条路线 -

routes.MapRoute( 
            "MyRoute1", // Route name 
            "{controller}/{action}/{something}/{name}/{id}/{myParameterA}",  
            new { controller = "MyController", action = "MyActionA", category = "something", name = "name", id = "id", myParameterA = "myParameterA" }); 
 
 
routes.MapRoute( 
            "MyRoute2", // Route name 
            "{controller}/{action}/{something}/{name}/{id}/{myParameterB}",  
            new { controller = "MyController", action = "MyActionB", category = "something", name = "name", id = "id", myParameterB = UrlParameter.Optional } ); 

我的 Controller 中的代码如下所示 -

    public ActionResult MyActionA(string something, string name, string id, string myParameterA) 
    { 
       //do cool stuff! 
    } 
 
    public ActionResult MyActionB(string something, string name, string id, string myParameterB) 
    { 
       //do awesome stuff! 
    } 

当我调用 MyActionB 时,最终参数 myParameterB 将作为 null 进入 Controller ,即使该参数位于 URL 中 - (示例:/MyController/MyActionB/aThing/aName/123/456)。

我确实希望最后一个参数(在我上面的示例中为“456”)是可选的。

MyActionA 工作正常。

如有任何建议,我们将不胜感激! 此外,关于 routes.MapRoute 的工作原理,是否有很好的引用资料? 谢谢!

请您参考如下方法:

这是因为一旦您将参数替换为路由本身中的字符串,就无法区分这 2 个路由。如果您向路由添加静态部分,您应该能够区分它们。

routes.MapRoute( 
        "MyRoute1", // Route name 
        "{controller}/{action}/{something}/{name}/{id}/firstroute/{myParameterA}",  
        new { controller = "MyController", action = "MyActionA", category = "something", name = "name", id = "id", myParameterA = "myParameterA" }); 
 
 
routes.MapRoute( 
        "MyRoute2", // Route name 
        "{controller}/{action}/{something}/{name}/{id}/secondroute/{myParameterB}",  
        new { controller = "MyController", action = "MyActionB", category = "something", name = "name", id = "id", myParameterB = UrlParameter.Optional } ); 

看看是否可行。