路由到同名但参数不同的动作 [英] Routing to the actions with same names but different parameters
问题描述
我有这组路线:
routes.MapRoute(
"IssueType",
"issue/{type}",
new { controller = "Issue", action = "Index" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
这是控制器类:
public class IssueController : Controller
{
public ActionResult Index()
{
// todo: redirect to concrete type
return View();
}
public ActionResult Index(string type)
{
return View();
}
}
为什么,当我请求 http://host/issue 我得到 当前的操作请求'索引' 在控制器类型 'IssueController' 上的以下操作方法之间存在歧义:
我希望第一个方法应该在没有参数时起作用,而第二个方法应该在指定参数时起作用.
why, when i request http://host/issue i get The current request for action 'Index' on controller type 'IssueController' is ambiguous between the following action methods:
I expect that first one method should act when there is no parameters, and second one when some parameter specified.
我哪里做错了?
UPD:可能重复:你能在 ASP.NET MVC 中重载控制器方法吗?
UPD 2:由于上面的链接 - 没有任何合法的方法可以使动作重载,是吗?
UPD 2: due to the link above - there is no any legal way to make action overloading, is it?
UPD 3:动作方法不能基于参数重载 (c) http://msdn.microsoft.com/en-us/library/system.web.mvc.controller%28VS.100%29.aspx一个>
UPD 3: Action methods cannot be overloaded based on parameters (c) http://msdn.microsoft.com/en-us/library/system.web.mvc.controller%28VS.100%29.aspx
推荐答案
我会有一个查找有效类型变量的 Index 方法
I would have one Index method that looks for a valid type variable
public class IssueController : Controller
{
public ActionResult Index(string type)
{
if(string.isNullOrEmpty(type)){
return View("viewWithOutType");}
else{
return View("viewWithType");}
}
}
如何创建一个自定义属性来查找特定请求值,如这篇文章 堆栈溢出
How about creating a custom attribute that looks for a specific request value as in this post StackOverflow
[RequireRequestValue("someInt")]
public ActionResult MyMethod(int someInt) { /* ... */ }
[RequireRequestValue("someString")]
public ActionResult MyMethod(string someString) { /* ... */ }
public class RequireRequestValueAttribute : ActionMethodSelectorAttribute {
public RequireRequestValueAttribute(string valueName) {
ValueName = valueName;
}
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {
return (controllerContext.HttpContext.Request[ValueName] != null);
}
public string ValueName { get; private set; }
}
这篇关于路由到同名但参数不同的动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!