Search code examples
.netasp.net-web-api2asp.net-web-api-routingasp.net-apicontroller

Web API 2 Routing


I'm fairly new to API Routing and trying to get my head around this problem.

Lets assume we have an List of Candy Bars.

I want todo the following:

ListAllCandyBars      --- api/Candy
ListCandyBar via ID   --- api/Candy/10
ListAllChocBars       --- api/Candy/Choc

Therefore we have 3 GETS

Default Get Get with ID Action Get

How would you expect to set up the Routes and Class. I only ever seem to be able to get either ListAllCandyBars and ListCandyBar via ID or ListAllCandyBars and ListAllChocBars working.

This is my current Route:

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

Using something like this:

public class DefaultController : ApiController
    {
        // GET: api/Default
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Default/5
        public string Get(int id)
        {
            return "value";
        }

        // GET: api/Default/ListSub
        public string ListSub(int id)
        {
            return "value";
        }

        // POST: api/Default
        public void Post([FromBody]string value)
        {
        }

        // PUT: api/Default/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/Default/5
        public void Delete(int id)
        {
        }
     }

Look forward to hearing from you and getting past this little issue. PS It might be my understanding of Controllers. Should I have a different controller for ListAllChocBars?

Regards

James


Solution

  • I was over complicating and going for route attributes only worked really well.