In my project I need to create a link with parameters, so I was doing like this :
var link = new Uri(Url.Link("GetUser", new { id = 1 }));
static List<Students> std = new List<Students>()
{
new Students(){id = 1, Nome = "Nathiel"},
new Students() {id = 2, Nome = "Barros"}
};
And them the method that would receive the id :
[Route("{id:int}",Name = "GetUser")]
[HttpGet]
public async Task<HttpResponseMessage> Get(int id)
{
var u = std.FirstOrDefault(x => x.id == id);
var response = new HttpResponseMessage();
response = Request.CreateResponse(HttpStatusCode.OK, u);
var task = new TaskCompletionSource<HttpResponseMessage>();
task.SetResult(response);
return await task.Task;
}
The problem is, the URL is not concatenate the second Route, "GetUser", and is coming like this : "http://localhost:52494/api/v1/Register/1"
.
Assuming the route prefix is api/v1/Register
[RoutePrefix("api/v1/Register")]
public class RegisterController : ApiController {
[HttpGet]
[Route("{id:int}",Name = "GetUser")] //Matches GET api/v1/Register/1
public async Task<IHttpActionResult> Get(int id) {
//...code removed for brevity
}
}
then that is by design.
The Route Name is used to identify the route template to use when generating the route.
If you want GetUser
in the URL then include it in the route template
[RoutePrefix("api/v1/Register")]
public class RegisterController : ApiController {
[HttpGet]
[Route("GetUser/{id:int}",Name = "GetUser")] //Matches GET api/v1/Register/GetUser/1
public async Task<IHttpActionResult> Get(int id) {
//...code removed for brevity
}
}