Reputation: 1569
So many people have asked the same question but I couldn't find a solution to my problem.
in postman when i call the 'http://localhost/api/GetById/2' i get the following error
No HTTP resource was found that matches the request URI http://localhost/api/GetById/2.
It works fine when I pass value 2 as a query string http://localhost/api/GetById/?id=2. Following is my WebApiConfig route parameter settings:-
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Following is my my API controller action method
[Route("~/api/GetById/")]
[HttpGet]
public HttpResponseMessage Get(int id)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(JsonConvert.SerializeObject(GetUsers(id)), "application/json");
return response;
}
Will please someone tell me what i am doing wrong here?
Upvotes: 1
Views: 1830
Reputation: 10693
Replace steve
with the controller name. You are mixing attribute routing and convention based routing. That is causing the routetable to barf. Since you use the route ~/api/getbyid/
it no longer has a controller reference from the convention based routing. So you need to do either all attribute routing or all convention based routing.
In addition you didnt take on the int
at the end of your route, so .net router couldn't parse the query string and put your integer
into your function call.
[RoutePrefix("api/Steve")]
public class SteveController :ApiControlller
{
[Route("GetById/{id:int}")]
[HttpGet]
public HttpResponseMessage Get(int id)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(JsonConvert.SerializeObject(GetUsers(id)), "application/json");
return response;
}
}
Upvotes: 0
Reputation: 8183
Change your route to:
[Route("~/api/GetById/{id}")]
See this https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/
You can also be very specific to tell the code where the id
value is coming from by using the [FromRoute]
attribute like the following:
public HttpResponseMessage Get([FromRoute]int id)
Upvotes: 1