我想设置一个路由,提交给带有前缀操作的 Controller 。
例如,我有一个用于服务提供商的 ProvidersController
,我有一个我想在 Providers Controller 中处理的 ProviderType
模型(它是一个轻量级对象我只是假设没有专门为这些小支持对象中的每一个设置新的 Controller ,因此我想将它们分组到 Providers Controller 中)。
因此,我的 ProvidersController
具有用于管理提供者的标准操作:
public class ProvidersController : ControllerBase
{
public ActionResult Index() { }
public ActionResult Create() { }
public ActionResult Edit(int id) { }
// ect ect
}
我也想在这里处理 ProviderTypes:
public class ProvidersController : ControllerBase
{
public ActionResult Index() { }
public ActionResult Create() { }
public ActionResult Edit(int id) { }
// ect ect
public ActionResult TypeIndex() { }
public ActionResult TypeCreate() { }
public ActionResult TypeEdit(int id) { }
// ect ect
}
一切都很好,希望我的路由“看起来像”嵌套了一个 Type:
~/Providers/Create
~/Providers/Types/Create
这是我想到的路线:
routes.MapRoute(
name: "ProviderTypes",
url: "Providers/Types/{action}/{id}",
defaults: new { controller = "Providers", action = "Index", id = UrlParameter.Optional }
);
但这需要我使用 ~/Providers/Types/TypeCreate
路由,我不喜欢这样。
有什么方法可以“拦截”此路由并向操作添加“类型”前缀,以便它正确映射到 Controller 操作,但按我喜欢的方式提供干净的 URL?
例如,我如何让 ~/Providers/Types/Create
映射到 ProvidersController.TypeCreate()
?
(一般来说,我试图避免属性路由,因为我希望所有路由定义都来自一个地方,而不是分散在各处)
最佳答案
您可以启用 ASP.NET MVC Attribute Routing
在RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes){
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//enabling attribute routing
routes.MapMvcAttributeRoutes();
//You can also combine attribute routing with convention-based routing.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
然后在你的 ProvidersController
[RoutePrefix("Providers"]
public class ProvidersController : ControllerBase {
//eg: GET Providers
[Route("")]
public ActionResult Index() {...}
//eg: GET Providers/Create
[Route("Create")]
public ActionResult Create() {...}
//eg: GET Providers/Edit/5
[Route("Edit/{id:int}")]
public ActionResult Edit(int id) {...}
// ...
//eg: GET Providers/Types
[Route("Types")]
public ActionResult TypeIndex() {...}
//eg: GET Providers/Types/Create
[Route("Types/Create")]
public ActionResult TypeCreate() {...}
//eg: GET Providers/Types/Edit/5
[Route("Types/Edit/{id:int}")]
public ActionResult TypeEdit(int id) {...}
// ...
}
关于asp.net-mvc - ASP.NET MVC 路由的操作前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35826508/