Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The current request for action {0} on controller type {1} is ambiguous

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;
    }
}
like image 366
Stan Avatar asked Jul 03 '13 20:07

Stan


1 Answers

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.

like image 113
Max Toro Avatar answered Oct 04 '22 08:10

Max Toro