c# - 路线模式与单独路线

标签 c# asp.net-mvc routes asp.net-mvc-routing

目前我有一个看起来像这样的 Controller :

public class MyController : Controller
{
    public ActionResult Action1 (int id1, int id2)
    {

    }

    public ActionResult Action2 (int id3, int id4)
    {

    }
}

正如您所看到的,我的两个 Controller 具有相同的参数“模式”,即两个不可为空的有符号整数。

我的路线配置如下所示:

routes.MapRoute(
    name: "Action2",
    url: "My/Action2/{id3}-{id4}",
    defaults: new { controller = "My", action = "Action2", id3 = 0, id4 = 0 }
);

routes.MapRoute(
    name: "Action1",
    url: "My/Action1/{id1}-{id2}",
    defaults: new { controller = "My", action = "Action1", id1 = 0, id2 = 0 }
);

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

但是,我的 Controller 操作比这两个要多得多,所以基本上我一直在为每个操作映射一条单独的路线,这让我觉得相当困惑。

我想知道是否可以使用两个参数而不是一个参数来执行类似默认路由的操作,例如:

routes.MapRoute(
    name: "Default2",
    url: "{controller}/{action}/{id1}-{id2}",
    defaults: new { controller = "Home", action = "Index", id1 = 0, id2 = 0 }
);

但是,鉴于我的参数并不总是命名为 id1id2 这将不起作用(错误是“参数字典包含参数的空条目”。我有办法做到这一点吗?(或者完全不同的方法哪个更好?)

感谢您的帮助!

编辑:根据迄今为止的答案,我的问题似乎有点误导。我特别想要一 strip 有通用参数的路由,因此不依赖于特定的参数名称。

我希望能够告诉路由管理器“嘿,如果您收到带有模式 {controller}/{action}/{parameter}-{parameter} 的请求,我想要您可以将这两个参数传递给指定的 Controller 和操作,无论其类型或名称如何!

最佳答案

看看默认路由:

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

关键位是UrlParameter.Optional。这允许您提供如下所示的操作:

public ActionResult Action1()

还有:

public ActionResult Action2(int id)

或者甚至:

public ActionResult Action3(int? id)

(后者允许参数为空值)

强制性警告

请记住,使用通用路由有一些注意事项。 MVC 中的模型绑定(bind)器极其宽容。它只是尝试从可以收集信息的任何来源填充尽可能多的参数。因此,即使您的特定路线仅通过 id1,也无法阻止狡猾的用户附加 ?id2=something 。如果模型绑定(bind)器可以使用它,它就会使用它。

关于c# - 路线模式与单独路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13382175/

相关文章:

c# - 如何选择项目 MVVM listview - Xamarin 表单

c# - 什么是 MVP-Passive View 和 MVP-Supervising controller

c# - 如何在 C# 中比较 XmlDocument 的两个 XmlNode?

c# - 如何将 Byte[](解码为 PNG 或 JPG)转换为 Tensorflows Tensor

jquery - ASP.Net MVC 在ajax发布后刷新另一个 View 中的其他元素

asp.net-mvc - 将 MVC 网站部署到 Azure

asp.net-mvc - 在 ASP.NET MVC View 中获取完整服务器路径的首选方法是什么?

javascript - 检查传单路线上是否存在点

javascript - 在ionic框架中设置 subview 和路由

php - Laravel 中的路由模型绑定(bind)和父子验证