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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.: stackoverflow.com/a/10471854/215068
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.