0

So imagine I have an API fo a car: I have a WheelsController and A WheelNutsController.

I want to be able to acces methods from WheelController:

GET /car/wheels/ - gets all the wheels
GET /car/wheels/{wheelId} - gets a single wheel, 
DELETE /car/wheels/{wheelId} - remove a wheel
GET /car/wheels/{wheelId}/speed - gets a speed of a single wheel

But in the same manner I want to be able to access the WheelNust methods from WheelNutController

GET /car/wheels/{wheelId}/wheelnuts - gets a list of wheel nuts associated with a wheel {wheelId} 
POST /car/wheels/{wheelId}/wheelnuts/{nutId}/tighten - some other method to work on a WheelNut.

if I do a routing like:

            config.Routes.MapHttpRoute(
                "SettlementSubAPI",
                "api/Wheels/{wheelId}/{controller}/{id}",
                new { id = RouteParameter.Optional , controller  = "WheelNuts"}
             );
             config.Routes.MapHttpRoute(
                "3wayroute",
                "api/{controller}/{id}/{AttributeName}",
                new { AttributeName = RouteParameter.Optional }
             );
             config.Routes.MapHttpRoute(
                    "DefaultAPI",
                    "api/{controller}/{id}",
                    new {  id = RouteParameter.Optional }
             );

i get "Multiple controller types were found" error.

How to manage such a routing ? At some point I'd like to add other controllers addressable in the same way like for example BrakeController to ba mapped to car/wheels/{wheelId}/brake/* etc.

Edit: using .net framework 4.7.2

azrael.pl
  • 85
  • 1
  • 8

1 Answers1

1

your urls are too complicated for the config to make them reliable. It's better to use an attribute routing, fix the config

config.MapHttpAttributeRoutes();

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

and add attributes like this to the actions

[HttpPost("~/car/wheels/{wheelId}/WheelNuts/{nutId}/Tighten")] 
public IActionResult WheelNutsTighten(int wheelId, int nutId)
...
Serge
  • 40,935
  • 4
  • 18
  • 45
  • You where partialy right, thanks for pointing in good direction. Actual problem was similar to disscused here https://stackoverflow.com/questions/26806395/mvc-route-attribute-error-on-two-different-routes?rq=1 I had all the routing done via Attribute routing, but the constraints on the actual methods where virtualy non-existend, so the mapping had multiple false hits, when it mapped a string literal to int parameter. Adding constraints to all routes, and removing all but DefaultApi and leaving config.MapHttpAttributeRoutes(); fixed my problem. – azrael.pl Apr 03 '23 at 11:35