Zapnologica
Zapnologica

Reputation: 22556

asp.net web api advanced routing

Can some one please help me with a route I am trying to setup

I have to know if I can and how to go about configuring a route list so

localhost/api/device/1/commands/turnOn

{hostname}/{api section}{I will multiple types of devices with diiferent commands}

So some examples:

The above are just random examples of things I want to do.

But the underlying structure is correct. I want to have multiple devices with device specific commands and options

I don't know how to portray this in a controller? I would think something along the long of a controller for each device The under that device I would have the different sections like command, info ,etc then under each one of those I woudl have the action methods.

But I dont know how to do that.

Any help would be greatly apperecited:

Also what is better practice:

[HttpGet]
    public HttpStatusCode Arm()
    {
        return HttpStatusCode.OK;
    }

    [HttpGet]
    public HttpStatusCode StayArm()
    {
        return HttpStatusCode.OK;
    }

    [HttpGet]
    public HttpStatusCode Disarm()
    {
        return HttpStatusCode.OK;
    }

or:

 [HttpGet]
    public HttpStatusCode Command(string command)
    {
        switch (command)
        {
            case "arm":
                {

                }
                break;
            case "disarm":
                {

                }
                break;                    
        }
        return HttpStatusCode.OK;
    }

Upvotes: 0

Views: 813

Answers (1)

user2635176
user2635176

Reputation:

Method 1 is better practice. It makes your code more readable, maintainable and testable.

You wont have a controller for each device. What you should have is one controller which queries the database or service for the device and then performs the action on that device.

You can prefix your controller actions with the following in order to get parameters from the route:

[HttpGet]
[Route("device/{deviceId}/commands/turnOff")]
public HttpStatusCode TurnOff(int deviceId)
{
    // 1. Find device by deviceId
    // 2. Turn the device off
    return HttpStatusCode.OK;
}

Upvotes: 2

Related Questions