c# - .NET MVC 自定义路由

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

我想知道我是否可以创建一个比 Controller 高一级的路由映射。典型的路由将包括“/controller/action/id”。我正在寻找的是“部分/ Controller / Action /id”或“ Controller /部分/ Action /id”之类的东西。我该怎么做?

最佳答案

没问题。只需创建一个路由,例如,其 URL 是

path/to/my/application/{controller}/{action}/{id}

...并像往常一样提供默认 Controller 和操作。

一个具体的例子是

context.MapRoute(
    "Admin_default",
    "admin/{controller}/{action}/{id}",
    new { controller = "AdminHome", action = "Index", id = "" }
);

例如,这将映射以下 URL:

/admin/                   => AdminHomeController.Index
/admin/adminhome/         => AdminHomeController.Index
/admin/other/             => OtherController.Index
/admin/statistics/view/50 => StatisticsController.View(50)

但请注意,如果您还有默认路由,例如:

context.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" }
);

...那么 Admin 路由中的 Controller 操作方法也可以通过此路由访问。使用 URL Routing Debugger确定地找出答案。

关于c# - .NET MVC 自定义路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1623605/

相关文章:

javascript - 如何验证 ajax 服务器计算的结果是否与用户的 UI 操作匹配?

ASP.NET 路由 : How to make routeConfig handle a more dynamic URL structure

c# - MVC 路由未保留在 RedirectToAction 上

javascript - ASP.NET MVC 路由 - domain.com/Events#!/12 到 domain.com/Events/12

c# - LINQ - 向数据上下文添加函数

c# - C# 使用表达式树生成分组后带有求和的 select 语句

c# - 为什么操作方法 DeleteConfirmed 使用模型 ID 而不是模型对象作为其参数?

asp.net-mvc - 在 MVC 6 Controller 中创建 session (使用 View ,使用 Entity Framework )

c# - 获取文档与整个存储库的差异匹配百分比 (C#)

c# - 以编程方式将数据插入word文件并保存在asp.net中