【发布时间】:2018-09-04 01:06:55
【问题描述】:
我正在研究 ASP.Net MVC 路由。我想创建一个将参数传递给操作的路由,而不管参数名称如何。我已经对此进行了一些阅读并尝试了不同的选项,但无法使其正常工作,所以想知道这是否可能?
这是我的一个例子:
我的 StudentController 中有两个操作方法
// First Action in StudentController
public ActionResult GetStudentByName(string name)
// Second Action in StudentController
public ActionResult GetStudentById(int id)
现在在我的路线配置中,我有:
// Get Student By Name
routes.MapRoute(
name: "StudentByName",
url: "Student/GetStudentByName/{name}",
defaults: new { controller = "Student", action = "GetStudentByName", name = "" }
);
// Get Student By Id
routes.MapRoute(
name: "StudentById",
url: "Student/GetStudentById/{id}",
defaults: new { controller = "Student", action = "GetStudentById", id = UrlParameter.Optional }
);
这很好用,但我必须为这两个动作定义两条路线。我的操作期望具有不同名称(名称和 ID)的参数。
我想要一个通用路由,既可以处理 Action 方法,又可以将参数传递给 action,像这样?
// Is this possible?
routes.MapRoute(
name: "AspDefault",
url: "{controller}/{action}/{GenericParamName}",
defaults: new { controller = "Home", action = "Index", GenericParamName = UrlParameter.Optional }
);
我已经尝试过了,但无法使其正常工作。如果 Action 和 Route 中的参数名不匹配,就好像没有通过...
是否可以用一条路由处理这两种操作方法?如果是的话怎么办?
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing