有关控制器类型的动作{0}当前请求{1}不明确 [英] The current request for action {0} on controller type {1} is ambiguous
问题描述
我有两个动作,我想我的路线 /用户
和 /用户/ {ID}
是不同的。然而,它引发了我的错误。
是否有可能实现这个八九不离十的事情,而无需手动创建的每个的路线,我将有将遵循类似的模式,并编写定制的路线为所有这些其他控制器似乎是多余的坏主意一般。
错误
有关行动控制器类型索引当前请求
UsersController'是下面的操作方法之间暧昧:
在类型System.Web.Mvc.ActionResult指数()
Api.Controllers.UsersController System.Web.Mvc.ActionResult
在类型Api.Controllers.UsersController指数(Int32)已
块引用>code
公共类UsersController:控制器
{
公众的ActionResult指数()
{
返回null;
} 公众的ActionResult指数(INT ID)
{
返回null;
}
}
解决方案您需要一个
ActionMethodSelector
:公共类RequiresParameterAttribute:ActionMethodSelectorAttribute { 只读字符串参数名称; 公共RequiresParameterAttribute(字符串参数名称){
this.parameterName =参数名称;
} 公众覆盖布尔IsValidForRequest(ControllerContext controllerContext,MethodInfo的MethodInfo的){
返回controllerContext.RouteData.Values [参数名称]!= NULL;
}
}和控制器:
公共类UsersController:控制器
{
公众的ActionResult指数()
{
返回null;
} [RequiresParameter(ID)]
公众的ActionResult指数(INT ID)
{
返回null;
}
}我不知道如果上述的工作,但应该给你一个想法。
I have two actions and I want my routes
/users
and/users/{id}
to be different. However it throws me error.Is it possible implement this sorta thing without manually creating every route, I will have other controllers that will follow similar pattern and writing custom routes for all of them seems redundant and bad idea in general.
Error
The current request for action 'Index' on controller type 'UsersController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult Index() on type Api.Controllers.UsersController System.Web.Mvc.ActionResult Index(Int32) on type Api.Controllers.UsersController
Code
public class UsersController : Controller { public ActionResult Index() { return null; } public ActionResult Index(int id) { return null; } }
解决方案You need an
ActionMethodSelector
:public class RequiresParameterAttribute : ActionMethodSelectorAttribute { readonly string parameterName; public RequiresParameterAttribute(string parameterName) { this.parameterName = parameterName; } public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) { return controllerContext.RouteData.Values[parameterName] != null; } }
And the controller:
public class UsersController : Controller { public ActionResult Index() { return null; } [RequiresParameter("id")] public ActionResult Index(int id) { return null; } }
I'm not sure if the above will work, but should give you an idea.
这篇关于有关控制器类型的动作{0}当前请求{1}不明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!