Search code examples
c#asp.net-web-apiasp.net-web-api-routing

ApiController get with id not working


I just started working with ApiController. I'm trying to do an HTTP GET sending an ID, but it is not working.

My ApiController:

[Route("api/Test")]
public class TestController : ApiController
{
    private myEntity db = new myEntity();

    [HttpGet]
    public HttpResponseMessage GetAll()
    {
        // Get a list of customers
        IEnumerable<Customer> customers = db.Customers.ToList();

        // Write the list of customers to the response body
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, customers);

        return response;
    }

    [HttpGet]
    public HttpResponseMessage GetById(int id)
    {
        // Get Customer by id
        Customer customer = db.Customers.Where(x => x.Id == id).FirstOrDefault();

        HttpResponseMessage response;

        if (customer == null)
        {
            response = Request.CreateResponse(HttpStatusCode.NotFound);
            return response;
        } else
        {
            response = Request.CreateResponse(HttpStatusCode.OK, customer);
        }

        return response;
    }

When I run it in the browser, the GetAll method work perfectly. However, when I try GetById:

http://localhost:53198/api/Test/1

It returns:

No HTTP resource was found that matches the request URI http://localhost:53198/api/Test/1

Does anyone know what I am doing wrong?


Solution

  • If using attribute routing you would need to make a few changes to make sure that action routes are distinct to avoid any route conflicts.

    [RoutePrefix("api/Test")]
    public class TestController : ApiController {
        private myEntity db = new myEntity();
    
        //GET api/Test
        [HttpGet]
        [Route("")]
        public IHttpActionResult GetAll() {
            // Get a list of customers
            var customers = db.Customers.ToList();    
            // Write the list of customers to the response body
            return OK(customers);
        }
    
        //GET api/Test/1
        [HttpGet]
        [Route("{id:int}")]
        public IHttpActionResult GetById(int id) {
            // Get Customer by id
            Customer customer = db.Customers.Where(x => x.Id == id).FirstOrDefault();
            if (customer == null) {
                return NotFound();
            }
            return Ok(customer);
        }
    }
    

    This assumes that attribute routing is enabled

    public static class WebApiConfig {
        public static void Register(HttpConfiguration config) {
            // Attribute routing.
            config.MapHttpAttributeRoutes();
    
            // Convention-based routing.
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
    

    Reference Attribute Routing in ASP.NET Web API 2