Steve Gaines
Steve Gaines

Reputation: 601

How Best To Overload A RESTful Service Method?

I have a RESTful Web API built using the ASP.NET MVC template. It's working nicely. I'm unsure how to elegantly arrange two methods with conflicting parameters. I have a Certifications table that lists my Microsoft certifications. I have an Exams table that lists the exams for each certification. There is a one-to-many relationship. When I created the ExamsController it automatically added a GetExams() method and a GetExam(int id) method. The GetExams method returns all the Exams records, the GetExam method returns the Exam record that matches id. So far so good. I wanted to add a GetExams(int certificationId) method to return all of the exams that relate to a specified certification. That's when the train left the tracks. It threw an error that there were conflicting methods which doesn't make sense to me because one is named GetExam with an int parameter and the other is named GetExams with an int parameter. (I think Microsoft has some design issues to improve in a future release of Web API). So I re-wrote the second method to be GetExams(int id, int extra) and I ignore the extra int parameter. It works, but it's not elegant, and I'm an elegant kind of guy. What is the best RESTful way of organizing these three methods?

Upvotes: 1

Views: 1935

Answers (1)

Jasen
Jasen

Reputation: 14250

Fix your URLs and use Attribute Routing

[HttpGet]
[Route("api/exams/{id}")]
public IHttpActionResult GetExams(int id) { }

[HttpGet]
[Route("api/certifications/{cid}/exams")]
public IHttpActionResult GetCertificationExams(int cid) { }

Upvotes: 4

Related Questions