You can add a name to the route attributes in your controller, and then use the IUrlHelper.RouteUrl extension IUrlHelper.RouteUrl to generate the URL.
For example, given the following web api controller:
[Route("api/[controller]")] public class UsersController : Controller { // GET: api/users [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/users/5 [HttpGet("{id}", Name ="UsersGet")] public string Get(int id) { return "value"; } //additional methods... }
You can create the url api/users/123 for a specific get action by id using @Url.RouteUrl("UsersGet", new { id = 123 }) .
The problem when using the extension method Url.Action is that if you have a controller, as in the above example, with two actions named "Get", this will use the route for the action without parameters and generate /api/Users?id=123 . However, if you comment on this method, you will see that @Url.Action("Get", "Users", new { id = 123 }) also gives the expected url.
source share