Home > Blockchain >  Route Confusion with Single Action
Route Confusion with Single Action

Time:10-27

I am clearly having issue understanding the routes here or trying to achieve which is not possible.

I have this in my RouteConfig:

 routes.MapRoute(
     name: "Explorer",
     url: "{controller}/{action}/{prefix}/{value}",
      defaults: new { controller = "Explorer", action = "Index", prefix ="", value = UrlParameter.Optional }
             );

And in Explorer Controller I have the following:

[RoutePrefix("Explorer")]
public class ExplorerController : Controller
{        
    public ActionResult Index()
    {
        return View();
    }

    [Route("id/{value}")]
    public ActionResult Import(decimal? importId)
    {
        return View();
    }

    [Route("text/{value}")]
    public ActionResult Import(string importWindow)
    {
        return View();
    }
}

One of the ACTION (Import) has different PREFIX such as window and id but whenever I try to access it (such as https://localhost/Explorer/Import/window/helloWorld OR https://localhost/Explorer/Import/id/200) it keeps giving me the following error

The current request for action 'Import' on controller type 'ExplorerController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult Import(System.Nullable`1[System.Decimal]) on type projectname.Controllers.ExplorerController System.Web.Mvc.ActionResult Import(System.String) on type projectname.Controllers.ExplorerController

I know it is ambiguous but I have a prefix which should make it non-ambiguous.

What am I doing wrong here and how to achieve this outcome if this is not the right way to do it?

CodePudding user response:

Apply the [Route()] attribute for action methods in the controller class:

[RoutePrefix("Explorer")]
public class ExplorerController : Controller
{
    // GET: Explorer
    public ActionResult Index()
    {
        return View();
    }

    // Example: https://localhost/Explorer/Import/id/200

    [Route("Import/id/{importId:decimal}")]
    public ActionResult Import(decimal? importId)
    {
        return View();
    }

    // Example: https://localhost/Explorer/Import/window/helloWorld

    [Route("Import/{text}/{importWindow}")]
    public ActionResult Import(string importWindow)
    {
        return View();
    }
}

Define only the Default route in the RegisterRoutes() method:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}
  • Related