Search code examples
asp.net-mvc-3asp.net-mvc-routingwcf-web-api

registering routes wcf web api


I have a problem with an Api I'm currently developing with WCF Web Api, this is the thing:

I want to register several resource classes as service contracts. So I have a RootResource from which I can access ChildResource1, ChildResource2, ChildResourceN.

Essentially what I want to do is perform a serie of http operations with the following route structure:

  1. GET /RootResource/{RootResouceId}/ChildResourceN/{ChildResourceNId} (this will get the Nth ChildResource from the RootResource)

My current resource registration:

routes.MapServiceRoute<ChildResource1>("RootResource");

And my operation is annotated within the resource as follows:

[WebGet(UriTemplate = "{RootResouceId}/ChildResource1/{ChildResource1Id}")]

However this approach is not convenient for me, because all my routes need to have the same pattern, the one I mentioned above.

If I want to register another resource now, lest say ChildResource2, then:

routes.MapServiceRoute<ChildResource2>("RootResource");

Notice that the base route is the same, and WCF Web Api doesn't allow this.


Solution

  • The "RootResource" passed into MapServiceRoute() has to map to a single type specified by T. So if you want to use a scheme as you deescribe you would need to create a single service contract and map everything onto that service contract. Fro the description I am not certain of {RootResouceId} maps to a specific item of a given type, ie all types are the same, in which cases it makes sense to put them in one contract or different types, in which case I would make this part of the service mapping, ie

    routes.MapServiceRoute<ChildResource1>("RootResource/Child1");
    routes.MapServiceRoute<ChildResource2>("RootResource/Child2");