我有一种情况,我希望ThisAction控制器看起来像这样:
public ActionResult Index()...
public ActionResult Index(int programId)...
public ActionResult Index(string programKey)...
目标是设置路线
www.website.com/ThisAction/< - 匹配第一功能
www.website.com/ThisAction/123< - 匹配第二功能
www.website.com/ThisAction/ABC< - 匹配第三功能
这可以在global.asx路由中设置吗?
答案 0 :(得分:4)
您需要使用带路由约束的属性路由来轻松获得灵活性。
[RoutePrefix("ThisAction")]
public class ThisActionController : Controller {
[HttpGet]
[Route("")] //Matches GET ThisAction
public ActionResult Index() {
//...
}
[HttpGet]
[Route("{programId:int}")] //Matches GET ThisAction/123
public ActionResult Index(int programId) {
//...
}
[HttpGet]
[Route("{programKey}")] //Matches GET ThisAction/ABC
public ActionResult Index(string programKey) {
//...
}
}
确保在 RouteConfig
中启用了属性路由public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
//...other code removed for brevity
//Attribute routes
routes.MapMvcAttributeRoutes();
//convention-based routes
//...other code removed for brevity
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
}
该路由将与基于约定的路由一起工作。
请注意,一旦在控制器上使用它,就必须在整个控制器上使用它。所以控制器要么都是基于约定的,要么都是属性路由。