Search code examples
c#asp.net-web-apiasp.net-web-api-routing

url.link error: A route named 'Default' could not be found in the route collection. Parameter name: name


I am working on a MVC application and trying to use the Url.Link function to build a working url.

Here's some relevant code:

In the RouteConfig.cs

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

The route I am trying to reach in the controller (the function's name is Manage - it accepts a parameter named id that is of type guid:

[HttpGet]
[Route("manage/{id:guid}")]

Call to Url.Link():

Url.Link("Default", new { Controller = "Users", Action = "Manage", id = aggregateId });

I have tried naming the the attribute as such:

[HttpGet]
[Route("manage/{id:guid}", Name="ManageUserRoute")]

Then calling Url.Link() like this:

url = Url.Link("ManageUserRoute", new { id = aggregateId });

I get the same error in the title using both methods. How do I correct this?


Solution

  • Your example is mixing both attribute routing and convention-based routing.

    Assuming the action is ActionResult Manage(Guid id) in the UsersController, you construct the link via convention-based routing like

    Url.Link("Default", new { controller = "Users", action = "Manage", id = aggregateId });
    

    Note the common/lower case names for controller and action “route values” used to compose the URL

    UPDATE

    After some investigating I also notice that you failed to mention that this is for Web API not MVC. The clue was that there is no Link method in the MVC version of UrlHelper.

    So more than likely you are getting that error because the default convention-based route for Web api is DefaultAPi not Default

    // Convention-based routing.
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    

    which is why it cannot find the Default route name in the route table for http route mappings. You need to check your WebApiConfig.cs file for the routes for your Web API.

    So you probably want

    Url.Link("DefaultApi", new { controller = "Users", action = "Manage", id = aggregateId });