【问题标题】:WebApi routing - many GET methodsWebApi 路由 - 许多 GET 方法
【发布时间】:2016-03-13 20:12:24
【问题描述】:

我有以下(标准)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 作为流派参数传递)。

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

我做错了什么?

【问题讨论】:

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


    【解决方案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;
    }
    

    【讨论】:

    猜你喜欢
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 2020-05-27
    • 1970-01-01
    相关资源
    最近更新 更多