Search code examples
asp.net-mvcasp.net-web-api2asp.net-web-api-routing

No HTTP resource was found that matches the request URI 'http://localhost/api/GetById/2'


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?


Solution

  • 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)