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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With