I am trying to learn the new MVC 6. I never used the Microsoft MVC framework before. I am trying to enhance an simple tutorial web API by adding links to different actions of my controllers using the URL (urlhelper) of the controller (Home controller showing what the API can do). But when I use:
this.Url.Action("Get", new {id = id});
I get a query string with the URL. I'd like a more restful-style URL.
I thought when using the attributes routing, I do not have to map a specific route like I see in old tutorials of WebApi.
Do I have to map a route ? What do I have to do to get a more restful URL style ?
You can add a name to the route attributes in your controller, then use the extension method 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 generate the url api/users/123
for the specific get by id action using @Url.RouteUrl("UsersGet", new { id = 123 })
.
The problem when using the Url.Action
extension method is that if you have a controller like in the example above with 2 actions named "Get", this will use the route for the action without parameters and generate /api/Users?id=123
. However if you comment that method, you will see that @Url.Action("Get", "Users", new { id = 123 })
also gives you the expected url.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With