vduret
vduret

Reputation: 13

How to dispatch two different Odata routes to the same EntitySetController<TEntity, TKey>?

Is it possible to have different entity sets (e.g. Cats and Dogs) being handled by the same controller (e.g. AnimalsController)?

public class AnimalsController : EntitySetController<Animal, int>
{
}

...

ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Animal>("Cats");
modelBuilder.EntitySet<Animal>("Dogs");

Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel();
config.Routes.MapODataRoute("ODataRoute", "odata", model);

Basically I need the ability to declare two different routes (/odata/cats and /odata/dogs) that will reach the same controller.

Once in the controller I will need a way to retrieve the route context to decide if the method willl return cats or dogs.

Can anyone point me to the right direction to achieve this result?

Upvotes: 1

Views: 2097

Answers (1)

Youssef Moussaoui
Youssef Moussaoui

Reputation: 12395

I'd generally recommend having one Web API controller per entity set you want to expose. But if you must really map requests to the same controller, here's how I'd do it. Define the following controller selector:

public class AnimalControllerSelector : DefaultHttpControllerSelector
{
    public override string GetControllerName(HttpRequestMessage request)
    {
        string controllerName = base.GetControllerName(request);
        if (controllerName == "Cats" || controllerName == "Dogs")
        {
            controllerName = "Animals";
        }
        return controllerName;
    }
}

Register it:

config.Services.Replace(typeof(IHttpControllerSelector), new AnimalControllerSelector());

and then access the entity set name within your controller with the following code:

string entitySetName = (ODataPath.Segments.First() as EntitySetPathSegment).EntitySetName;

Hope that helps.

Upvotes: 3

Related Questions