简体   繁体   中英

WebApi routing - many GET methods

I have the following (standard) WebApiConfig:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
    // Configure Web API to use only bearer token authentication.
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

and the following api controller:

[RoutePrefix("api/books")]
public class BooksController : ApiController
{
    // GET api/Books
    [Route("")]
    public IQueryable<string> GetBooks()
    {
        return null;
    }

    // GET api/Books/5
    [Route("{id:int}")]
    public async Task<IHttpActionResult> GetBook(int id)
    {

        return Ok();
    }

    [Route("{id:int}/details")]
    public async Task<IHttpActionResult> GetBookDetail(int id)
    {
        return Ok();
    }

    [Route("abc")]
    public IQueryable<string> GetBooksByGenre(string genre)
    {
        return null;
    }

    [Route("~api/authors/{authorId}/books")]
    public IQueryable<string> GetBooksByAuthor(int authorId)
    {
        return null;

    }
}

It found appropriate method when I call

  • api/books
  • api/books/1
  • api/books/1/details

but it can't find api/books/abc .

If I change [Route("abc")] to [Route("{genre}")] it works (pass abc as genre parameter).

But I need to have many GET methods with different names.

What did I do wrong?

Try

// GET api/Books/genres/horror
[Route("genres/{genre}")]
public IQueryable<string> GetBooksByGenre(string genre)
{
    return null;
}

Or even

// GET api/genres/horror/books
[Route("~api/genres/{genre}/books")]
public IQueryable<string> GetBooksByGenre(string genre)
{
    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM