Type /api/users/:id/cars/:id



  • How to correctly implement the /api/users/:id/cars/:id.

    Let's say we have models. User and Car (with one to many):

    public class User
    {
        public int Id { get; set; }
    }
    

    public class Car
    {
    public int Id { get; set; }

    public int UserId { get; set; }
    public virtual User User { get; set; }
    

    }

    UsersController:

    public class UsersController : ApiController
    {
    [ResponseType(typeof(User))]
    public IHttpActionResult GetUser(int id)
    {
    User user = db.Users.Find(id);
    if (user == null)
    {
    return NotFound();
    }

        return Ok(user);
    }
    //тут все остальные методы
    

    }

    We have CarsController:

    public class CarsController : ApiController
    {
    [ResponseType(typeof(Car))]
    public IHttpActionResult GetCar(int id)
    {
    Car car = db.Cars.Find(id);
    if (car == null)
    {
    return NotFound();
    }

        return Ok(car);
    }
    //тут все остальные методы
    

    }

    In order to obtain a specific user, we shall contact the /Users/:id route.

    In order to get a specific car, we're on route /Cars/:id

    How do you get a specific user car? Add an additional method to the user counter?



  • In fact, adding such a route to the controller where it will be more comfortable.

    There's nothing to do with putting all the routes into a single controller, not smashing them differently. But controllers may have their dependence - and it makes sense to group actions so that these relationships are smaller.

    In your case, all three actions (as long as) depend only on the database, so the correct way to place them on the counter-ellers is the question of idling. Once the controllers cease to be so trivial, their dependence will help group actions in the most beautiful way.

    And to make it easier to move from one controller to another, I suggest you use it. http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2 :

    [Route("api/users/{id}")]
    [ResponseType(typeof(User))]
    public IHttpActionResult GetUser(int id) { ... }
    

    [Route("api/cars/{id}")]
    [ResponseType(typeof(Car))]
    public IHttpActionResult GetCar(int id) { ... }

    [Route("api/users/{userid}/cars/{id}")]
    [ResponseType(typeof(Car))]
    public IHttpActionResult GetCar(int id, int userid) { ... }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2