Reputation: 898
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?
Upvotes: 4
Views: 11111
Reputation: 52366
If your route name is Default, or whatever other name, make sure you specify it in the Name property.
Example:
[Route("{id:int}", Name="Default")]
public async Task<IHttpActionResult> Get(int id)
...
return CreatedAtRoute("Default",
new { id = x },
_mapper.Map<MyModel>(talk));
Upvotes: 1
Reputation: 1758
For MVC Use this
Url.Action("inspsrc")
Solved the same problem for me.
Upvotes: 0
Reputation: 246998
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 });
Upvotes: 6