【发布时间】:2011-08-01 06:50:10
【问题描述】:
我正在重写这个问题,因为到目前为止的答案告诉我,我对它的定义不够好。我将在下面留下原始问题以供参考。
设置路由时,您可以为不同的 url/路由部分指定默认值。让我们考虑 VS 向导生成的示例:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "DefaultPage", action = "Index", id = UrlParameter.Optional } // Parameter defaults
在此示例中,如果未指定控制器,将使用 DefaultPageController,如果未指定操作,则将使用“索引”操作。
url 通常看起来像:http://mysite/MyController/MyAction。
如果 Url 中没有类似这样的操作:http://mysite/MyController,则将使用索引操作。
现在假设我的控制器 Index 和 AnotherAction 中有两个动作。对应的url分别是http://mysite/MyController和http://mysite/MyController/AnotherAction。我的“索引”操作接受一个参数 id。因此,如果我需要将参数传递给我的索引操作,我可以这样做:http://mysite/MyController/Index/123。请注意,与 URL http://mysite/MyController 不同,我必须明确指定 Index 操作。我想要做的是能够通过http://mysite/MyController/123 而不是http://mysite/MyController/Index/123。我不需要这个 URL 中的“索引”我希望 mvc 引擎识别,当我要求 http://mysite/MyController/123 时,123 不是一个动作(因为我没有用这个名称定义一个动作),而是一个参数我的默认操作“索引”。如何设置路由来实现这一点?
以下是问题的原文。
我有一个控制器,其中定义了两种方法
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(SomeFormData data)
{
return View();
}
这使我可以在用户导航到此 url (GET) 以及随后发回表单 (POST) 时像 http://website/Page 这样处理 Url。
现在,当我处理回帖时,在某些情况下我想将浏览器重定向到这个网址:
http://website/Page/123
其中 123 是某个整数,我需要一种方法来在我的控制器中处理此 url。
如何设置路由,这样才有效?目前我有向导生成的“默认”路由,如下所示:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "DefaultPage", action = "Index", id = UrlParameter.Optional } // Parameter defaults
我尝试像这样添加另一个控制器方法:
public ActionResult Index(int id)
{
return View();
}
但这不起作用,因为引发了模棱两可的动作异常:
当前对“索引”操作的请求 在控制器类型“PageController”上 在以下之间是模棱两可的 行动方法: System.Web.Mvc.ActionResult Index() on 类型 PageController System.Web.Mvc.ActionResult PageController 类型上的索引(Int32)
我必须补充一点,我在这个控制器中还有其他操作。如果我不这样做,This 会起作用。
【问题讨论】:
标签: asp.net-mvc routing url-routing asp.net-mvc-routing