【问题标题】:Custom routing within an area区域内的自定义路由
【发布时间】:2010-09-27 08:41:50
【问题描述】:

我有一个名为 Members 的区域,并且在 MembersAreaRegistration 文件中注册了以下路由:

context.MapRoute(
     "Members_Profile",
     "Members/Profile/{id}",
     new { controller = "Profile", action = "Index", id = UrlParameter.Optional },
     new string[] { "MyProject.Web.Mvc.Areas.Members.Controllers" }
     );

context.MapRoute(
     "Members_default",
     "Members/{controller}/{action}/{id}",
     new { controller = "Home", action = "Index", id = UrlParameter.Optional },
     new string[] { "MyProject.Web.Mvc.Areas.Members.Controllers" }
     );

我希望能够映射以下 URL:

~/Members (should map ~/Members/Home/Index )
~/Members/Profile/3 (should map ~/Members/Profile/Index/3)

使用此路由注册,一切正常。但是,我添加了以下网址:

~/Members/Profile/Add 

我得到了错误:

“参数字典包含一个 null 条目,用于 'MyProject.Web.Mvc.Areas 中的方法 'System.Web.Mvc.ActionResult Index(Int32)' 的不可为空类型 'System.Int32' 的参数 'id' .Members.Controllers.ProfileController'。可选参数必须是引用类型、可空类型或声明为可选参数。"

我也想要网址

~/Members/Profile/Edit/3

为了让所有这些 URL 正常工作,我应该修改什么?

【问题讨论】:

    标签: asp.net-mvc-2 asp.net-mvc-routing asp.net-mvc-areas


    【解决方案1】:

    您需要在已定义的路线之前添加几条额外的路线。这是因为这些是您希望在您已经拥有的更通用的路线之前选择的特定路线。

    context.MapRoute(
         "Members_Profile",
         "Members/Profile/Add",
         new { controller = "Profile", action = "Add" },
         new string[] { "MyProject.Web.Mvc.Areas.Members.Controllers" }
         );
    
    context.MapRoute(
         "Members_Profile",
         "Members/Profile/Edit/{Id}",
         new { controller = "Profile", action = "Edit", id = UrlParameter.Optional },
         new string[] { "MyProject.Web.Mvc.Areas.Members.Controllers" }
         );
    

    【讨论】:

    • 我按照您的建议做了一些修改。现在我使用的路由如下(顺序很重要):1.“Members/Profile/Add”2.“Members/Profile/{id}”3.“Members/{controller}/{action}/{ id}" 我去掉了 Edit 的路径,因为它被最后一个也是最通用的路径覆盖了。感谢您的帮助
    • 很高兴能提供帮助。请将问题标记为已回答,以便其他人也能找到它。
    猜你喜欢
    • 2016-02-20
    • 2016-05-28
    • 2017-02-21
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多