Bart
Bart

Reputation: 2341

ASP.NET web api routing of two methods with the same declaration

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

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

Upvotes: 0

Views: 815

Answers (3)

Nadav Lebovitch
Nadav Lebovitch

Reputation: 690

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

Upvotes: 0

James World
James World

Reputation: 29796

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.

Upvotes: 7

Denis Agarev
Denis Agarev

Reputation: 1529

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.

Upvotes: 0

Related Questions