0
votes

I'm new to Asp.net MVC and to Web APIs, just learning it.

lets say that we have

Models:

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
}

public class Course
{
    public int CourseID { get; set; }
    public string CourseName { get; set; }

    public IEnumerable<int> StudentIds { get; set; }
}

controllers:

  1. User Controller - implements Post, Put, Get, Delete
  2. Course Controller - implements Post, Put, Get, Delete

each controller uses some kind of repository to get/add/remove/update data
lets say:
courses Repository is static Dictionary<'int, Course> Courses
students Repository is *static Dictionary<'int, Student> Students *

We do not use Entity Framework!

Custom Routing

Post /api/courses/{courseid}/users/{userid}
this should go to Course Controller and add the user id to the list

[Route("api/courses/{CourseID}/students/{StudentID}")]
[HttpPost]
public HttpResponseMessage AddStudentToCourse(int CourseID, int StudentID) 
{ 
    // adding student id to the course
    ... 
}

Questions:

  1. should i use custom route to add the mapping between courses and users
  2. should i check if the student exists ? or this is kind of an agreement with the client that the input is valid
  3. if we do check - who should do it ? the controller ? the model ? some kind of data access layer?
  4. if its the CourseController / CourseModel that means that it should "know" the two repositories (the courses repository and the students repository) right ?
1

1 Answers

0
votes

I'll try to answer your questions in order, but remember that this kind of questions can be answered on opinions, personal preference, and personal experience, so you'll likely get different answers:

  1. In general you should avoid attribute routing, but if this an exception and fits in your routing pattern: go for it.
  2. You should always ensure the integrity of your data and implement your data access in that way. If the client misuses your service it can damage your data integrity. If the student exists give him a HTTP 200 or 201 and if the student does not exist give him one of the HTTP 400 errors (f.e. a 404). As a rule of thumb: Mistrust your client and check and validate the data it is sending to your API.
  3. I would do it in a data access layer. You should go with the idea of a thing controller, meaning that you should avoid a lot of operations in your controller. Your model is just a representation of your data. It should not contain any logic to find out if a specific entity exists or not.
  4. I don't know if I get your question right, but it should be answer with point 3.

Hope that this will answer most of your questions.