Linking using urlhelper in MVC 6 (vNext)

I am trying to learn the new MVC 6. I have never used the Microsoft MVC framework before. I am trying to improve a simple web-based learning interface by adding links to various actions of my controllers using the URL (urlhelper) of the controller (the main controller shows what the API can do). But when I use:

this.Url.Action("Get", new {id = id}); 

I get a query string with a url. I need a more relaxed style URL.

I thought that when using attribute routing, I don’t need to map a specific route, as I see in the old WebApi tutorials.

Do I need to map a route? What do I need to do to get a more relaxed URL style?

+5
source share
1 answer

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.

+3
source

All Articles