WebApi路由 - 许多GET方法

时间:2016-03-13 20:12:24

标签: c# asp.net-web-api asp.net-web-api2 asp.net-web-api-routing

我有以下(标准)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 }
    );
}

和以下api控制器:

[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;

    }
}

我打电话时找到了合适的方法

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

但找不到api/books/abc

如果我将[Route("abc")]更改为[Route("{genre}")]则可以正常工作(将abc作为genre参数传递)。

但是我需要有许多不同名称的GET方法。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

尝试

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

甚至

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