简体   繁体   中英

Web Api controller routing

I have a ConfigurationController with the default routing specified in the static Register method

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

The POST method of this endpoint creates a new configuration with a string id which is accessible via the url - 'api/configuration/newid'.

Each configuration can have a 'Task' associated with it. I would now like to expose CRUD operations for the task via the 'TaskController'. So if I want to create a new task for 'newid' I can do it by POSTing at 'api/configuration/newid/task'

I have no clue how to specify the routing for this in my Web API project.

  • What should the routing look like?
  • Also is this the right approach or should I instead expose the tasks via an explicit endpoint 'api/task' although tasks cannot exist in isolation. They are always bound to a configuration.

WebAPI is set up to be RESTful; that is, you use HTTP Verbs to talk to your controllers as opposed to named actions (ie, newconfig ).

So, to go the route you're already going, instead of hitting api/configuration/newconfig/task , you might just hit api/configuration and send requests with an HTTP POST verb. Then, the message you send might include what you're creating, for example:

{
  type: 'Task',
  data: {
  }
}

However, it would be a better idea to separate Tasks into their own controller, ie, TasksController , with their own GET, PUT, POST, DELETE verbs that act only on Tasks . Then, you would create new Tasks by calling api/Tasks/ with the message body being your desired task.

What should the routing look like?

routeTemplate: "api/configuration/{id}/task"

Also is this the right approach or should I instead expose the tasks via an explicit endpoint 'api/task' although tasks cannot exist in isolation. They are always bound to a configuration.

I think you've answered this when you state Each configuration can have a 'Task' associated with it.

If you keep your controllers 'light' and ensure the business logic is held somewhere else, adding new routes/controllers/actions becomes trivial.

If you wanted to, you could keep this in a ConfigurationTasks controller while still having a Configuration and Task controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM