1
votes

I am new to MVC WebAPI with EF4. I am wondering if it's better to split a large controller with multiple GET and/or PUT methods into multiple controllers in order to avoid "Multiple actions were found that match the request" error. I prefer to only use VERB-based route pattern "api/controller/id" as follows.

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
"Api",
"api/{controller}/{id}",
new { id = RouteParameter.Optional }
);

For example, I have two domain objects, Doctor and Patient. A ClinicController has the following actions:

getDoctors()
getPatientCohort(int doctorId) 
getPatientPrimaryDr(int patientId) 
getPatientDoctors(int patientId, int clinicId)
getPatients()
getPatient(int patientId)
putDoctor(Doctor doctor)
putPatient(Patient patient)
createDoctor(Doctor doctor)
createPatient(Patient patient)

Should I split this controller into DoctorController and PatientController so that each controller only deals with one domain object. Since the Patient Cohort is an association class, should getPatientCohort(int doctorId) be a method of PatientController or DoctorController? Thanks.

1

1 Answers

0
votes

In my opinion (and I'm explicitly stating this), you should create separate controllers for each model. It really depends on the purpose of the actions themselves, but I can probably guess the intentions and roughly split it up.

The Put and Create methods should reside in their own controller, because this (again, I assume) has nothing to do with the Clinic. Patients and Doctors just get created or updated (replaced), which is perfectly fine in their own controller. Should a patient or doctor be assigned to a clinic, there should be a separate action inside the Clinic controller which does this.

Any actions which has the Patient model as a basis, and retrieves associated models should also reside in the PatientController; analogous for the Doctor model.

So in essence it boils down to this:

  • Any model specific actions should be in the controller of that model.
  • Any model specific actions which retrieve associated models should reside in the controller of the main model.
  • Any binding actions can reside in either of the controllers which bind the two together.

This is similar to the way the OData framework handles actions and associations, and thus I'm more accustomed to implementing it that way. Hopefully this clears some things up for you (or at least provides some guidelines).