How to map WebAPI routes correctly

前端 未结 3 1531
抹茶落季
抹茶落季 2020-12-24 13:51

I\'m building an API for a Twitter like site using Web API and have trouble with mapping the routes

I have the following actions for the User controller:

<         


        
3条回答
  •  無奈伤痛
    2020-12-24 14:33

    Given the flexibility you want you should take a look at

    Attribute Routing in ASP.NET Web API 2

    In WebApiConfig.cs enable attribute routing like

    // Web API routes
    config.MapHttpAttributeRoutes();
    

    In UserController

    Note given the names of actions Friends, Followers and Favorites they imply returning collections rather than single user

    [RoutePrefix("api/users")]
    public class UserController: ApiController {
    
        //eg: GET api/users?firstname={firstname}&lastname={lastname}
        [HttpGet]
        [Route("")]
        public User Get([FromUri]string firstname,[FromUri] string lastname) {...}
    
        //eg: GET api/users/{id}
        [HttpGet]
        [Route("{id:guid}")]
        public User Get(Guid id){...}
    
        //eg: GET api/users/{id}/friends
        [HttpGet]
        [Route("{id:guid}/friends")]
        public IEnumerable Friends(Guid id){...}
    
        //eg: GET api/users/{id}/followers
        [HttpGet]
        [Route("{id:guid}/followers")]
        public IEnumerable Followers(Guid id){...}
    
        //eg: GET api/users/{id}/favorites
        [HttpGet]
        [Route("{id:guid}/favorites")]
        public IEnumerable Favorites(Guid id){...}
    }
    

提交回复
热议问题