0

I am using attribute routing with the following routes:

[RoutePrefix("api/books/{id}")]
public BooksController : ApiController
{
    [Route("")]
    public IHttpActionResult GetByTitle(int id,string title);

    [Route("")]
    public IHttpActionResult GetByTitleAuthorIsbn(int id,string title, string author, string isbn);
}

if the user goes to this route:

GET api/boos/1?title=abc&author=xyz

then web api will route this url to the default GET method i.e.

public IHttpActionResult GetByTitle(int id,string title);

What I would like to happen is that in the above mentioned scenario a 404 should be returned because the api doesn't have a route that accept title and author.

A couple of suggested solutions is to add the parameters in the route so

[RoutePrefix("api/books/{id}")]
public BooksController : ApiController
{
    [Route("{title}")]
    public IHttpActionResult GetByTitle(int id,string title);

    [Route("{title}/{author/{isbn}}")]
    public IHttpActionResult GetByTitleAuthorIsbn(int id,string title, string author, string isbn);
}

Another solution will be to add the method name in the route so

[RoutePrefix("api/books/{id}")]
public BooksController : ApiController
{
    [Route("byTitle")]
    public IHttpActionResult GetByTitle(int id,string title);

    [Route("byTitleAuthorIsbn")]
    public IHttpActionResult GetByTitleAuthorIsbn(int id,string title, string author, string isbn);
}

I would like to know if there is another solution as I am not a fan of "polluting" the route with extra route parameters or add method names in the route.

Please note that combining the two methods in one method is not the solution I am looking for. These 2 routes must stay 2 separate routes.

The example I show here is about books but it can be applied to anything so I said books just for argument sake.

Update:

This question is not a duplicate to this question as I have already included the answer in my question. I am looking for more alternatives.

Community
  • 1
  • 1
Sul Aga
  • 6,142
  • 5
  • 25
  • 37
  • I think you need to rethink your url structure. Why `GetByTitle` and at the same time supply a `id`? – Martin Aug 26 '15 at 10:18
  • The example I show here is about books but it can be applied to anything so I said books just for argument sake – Sul Aga Aug 26 '15 at 10:21
  • possible duplicate of [Multiple GET verb on single route with different parameter name Web Api](http://stackoverflow.com/questions/19296374/multiple-get-verb-on-single-route-with-different-parameter-name-web-api) – Martin Aug 26 '15 at 10:38
  • Please check latest update – Sul Aga Aug 26 '15 at 14:50
  • There is no constraint on your `id`, which essential means that it can be anything. But I don't think that you'll be able to do what you want without some heavy customisation. – Martin Aug 26 '15 at 18:41

0 Answers0