Search code examples
c#asp.net-mvc-5asp.net-web-api-routingasp.net-web-api2

Web API 2 Attribute Routing Clash


I'm having issues getting my head around how route selection works. I have two route attributes set which are clashing with each other. They Are

[Route("{apikey}/Parent/{parentID}/Children/ChildrenDataFormat")]
[Route("{apikey}/Parent/{parentID}/{dataSelectionTypeA}/{dataSelectionTypeB}")]

The first route's last two parts are hard coded and will never change. The second route will bind into the method parameters.

If I remove the second route then the first route works fine but otherwise I get a 404. I presume the Route Matching is seeing a Guid followed by "Parent" and then ignoring the fact that "Children" and "ChildrenDataFormat" should be present and instead seeing 3 things follow so route 2 is a match.

If this a correct assumption and is there an obvious fix to make this work?


Solution

  • I'm still not sure what the exact issue was but I've managed to fix it by adding route constraints to all my variables. I.E my routes now look like

    [Route("{apikey:guid}/Parent/{parentID:guid}/Children/ChildrenDataFormat")]
    [Route("{apikey:guid}/Parent/{parentID:guid}/{dataSelectionTypeA:guid}/{dataSelectionTypeB:guid}")]