user156888
user156888

Reputation:

web api routing

I have the following url:

localhost/api/machine/somecode/all

I have the following controller:

 public class MachineController : ApiController
{
    public IEnumerable<Machine> Get()
    {
        return new List<Machine>
                   {
                       new Machine
                           {
                               LastPlayed = DateTime.UtcNow,
                               MachineAlertCount = 1,
                               MachineId = "122",
                               MachineName = "test",
                               MachinePosition = "12",
                               MachineStatus = "test"
                           }
                   };
    }

    public IEnumerable<Machine> All(string code)
    {
        return new List<Machine>
                   {
                       new Machine
                           {
                               LastPlayed = DateTime.UtcNow,
                               MachineAlertCount = 1,
                               MachineId = "122",
                               MachineName = "test",
                               MachinePosition = "12",
                               MachineStatus = "test"
                           }
                   };
    }
}

and the following routes:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
          name: "MachineApi",
          routeTemplate: "api/machine/{code}/all"
      );

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


    }
}

but for some reason it's not resolving - any glaringly obvious reason why?

Upvotes: 1

Views: 5732

Answers (2)

Mark Jones
Mark Jones

Reputation: 12194

Yeah by using the Method name All you are inferring an Action, you also need to indicate the controller to match to so this would probably work:

config.Routes.MapHttpRoute(
      name: "MachineApi",
      routeTemplate: "api/machine/{code}/all",
      defaults: new { Action = "All", Controller = "Machine" }
  );

Upvotes: 2

Gaz Winter
Gaz Winter

Reputation: 2989

Where is it getting code from in this line?

 routeTemplate: "api/machine/{code}/all"

I am assuming that is the route thats failing.

Do you not need a defaults: setting?

In fact wouldn't this default to:

 api/machine/all/{code}

Have you tried looking in the Net tab on Firefox? This will tell you the route that its tried to go to.

Upvotes: 0

Related Questions