简体   繁体   English

WebApi路由-许多GET方法

[英]WebApi routing - many GET methods

I have the following (standard) WebApiConfig: 我有以下(标准)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: 和以下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;

    }
}

It found appropriate method when I call 我打电话时发现合适的方法

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

but it can't find api/books/abc . 但找不到api/books/abc

If I change [Route("abc")] to [Route("{genre}")] it works (pass abc as genre parameter). 如果我将[Route("abc")]更改为[Route("{genre}")]则可以正常工作(将abc作为类型参数传递)。

But I need to have many GET methods with different names. 但是我需要使用不同名称的许多GET方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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