MVC路由 - 参数名称问题

Jim*_*meh 10 c# model-view-controller asp.net-mvc routing url-routing

我正在寻找有关使用C#在MVC中路由的一些信息.我目前非常了解MVC中的路由基础,但我正在寻找的东西有点难以找到.

实际上,我想要找到的是一种定义采用单个参数的单一路径的方法.

我在网上找到的常见例子都是基于这个例子

routes.MapRoute(
    "Default",
    "{controller}.mvc/{action}/{id}"
    new { controller = "Default", action="Index", id=""});
Run Code Online (Sandbox Code Playgroud)

通过映射此路由,您可以映射到任何控制器中的任何操作,但是如果要将任何内容传递给操作,则必须将方法参数称为"id".如果可能的话,我想找到解决这个问题的方法,这样我就不必经常指定路由只是为了在我的动作中使用不同的参数名称.

有没有人有任何想法,或找到解决方法?

Cur*_*tis 7

如果您想拥有不同的参数名称保持相同的路由变量,请使用FromUri属性,如下所示:

public ActionResult MyView([FromUri(Name = "id")] string parameterThatMapsToId)
{
   // do stuff
}
Run Code Online (Sandbox Code Playgroud)

在您的路线中,您只需要:

routes.MapRoute(
  "Default",
  "{controller}.mvc/{action}/{id}"
  new { controller = "Default", action="Index", id=""});
Run Code Online (Sandbox Code Playgroud)


Tim*_*ott 5

我认为你不能完全按照你的要求去做.当MVC调用一个动作时,它会查找路径中的参数,请求参数和查询字符串.它总是希望匹配参数名称.

也许好的旧查询字符串将满足您的需求.

~/mycontroller/myaction/?foobar=123
Run Code Online (Sandbox Code Playgroud)

会将123传递给此操作:

public ActionResult MyAction(int? foobar)
Run Code Online (Sandbox Code Playgroud)


Edu*_*eni 0

您可以根据自己的喜好构建路线

routes.MapRoute(
    "Default",
    "{controller}.mvc/{action}/{param1}/{param2}/{param3}"
    new { controller = "Default", action="Index", param1="", param2="", param3=""});
Run Code Online (Sandbox Code Playgroud)

另外,看看这篇文章,它在评论部分包含所有类型的示例