0

I'm creating an api using Asp.net web api. I have controller BookController with two methods:

  • GetBook(int id) which returns book with given id and
  • GetBook(int userId) which returns all books of given user

If I call localhost/book/3 there is ambiguity in which method to call.How can I differentiate the two methods?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Bart
  • 2,301
  • 3
  • 29
  • 27

3 Answers3

7

Forget hacking, this is common sense. For the sanity of your users and developers just change the routes and the method names to clearly disambiguate these different operations. One solution might be to Map /user/3/books and books/3 to GetBooksByUser and GetBooks respectively. Makes the code and URIs more readable.

James World
  • 29,019
  • 9
  • 86
  • 120
0

I would have 2 controllers: Books and Users. For Books: api/books/3 will bring book #3, and for Users: api/users/3 will bring user #3.

Did you check out the basic tutorials on ASP.NET Web API? They're great, I've followed them and it makes all very simple:

http://www.asp.net/web-api/overview

Nadav Lebovitch
  • 690
  • 6
  • 8
0

There is a hacky way in using different http verbs

[HttpGet]
public int GetUsers(int i) { return 0; }

[HttpPost]
public int GetBooks(int i) { return 1; }

But I think use should add controller or param.

Denis Agarev
  • 1,531
  • 4
  • 17
  • 34
  • This will not work with the routes WebAPI uses out of the box. It use a name matching semantic that looks for a method starting with "Get..." when an http get comes in. So on post it searches for a method named "Post..." and won't see `GetBooks` See, e.g.: http://stackoverflow.com/a/10471854/215068 – EBarr Jun 01 '12 at 18:25