我需要在某些控制器之前添加一个“路径名”,以阐明其用途。
例如,当前:
/news/create
,
/news/edit
,
/event/create
,
/event/edit
,
我希望他们的路由器可以
/request/news/create
,
/request/news/edit
,
/request/event/create
,
/request/event/edit
我试图在 RouteConfig.cs
中添加以下代码 routes.MapRoute(
name: "Api",
url: "request/{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
其中一个控制器 EventController.cs
public class EventController : Controller{
[HttpPost]
public ActionResult Edit(int id, Events eventModel){
//code
}
[HttpPost]
public ActionResult Create(Events eventModel){
//code
}
}
我在这里遇到问题:
/request/event/create
404错误
/request/event/edit/1
有效!
/event/create
有效!
/event/edit/1
有效!
所以,我的问题是为什么/request/event/create
不起作用以及如何解决?
据我所知,在创建动作上方添加[Route("request/event/create")]
可以使其正常工作。
---------更新--------
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Index", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Api",
url: "request/{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
}
}
答案 0 :(得分:2)
已注册路线的顺序很重要。将更具体的路线移到通用路线之前
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Api",
url: "request/{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Index", action = "Index", id = UrlParameter.Optional }
);
}
}