是否可以让同一个控制器(例如AnimalsController)处理不同的实体集(例如Cats and Dogs)?
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);
基本上我需要能够声明两条到达同一控制器的不同路线(/ odata / cats和/ odata / dogs)。
一旦进入控制器,我将需要一种方法来检索路线上下文,以确定该方法是否会返回猫或狗。
有人能指出我正确的方向来实现这个结果吗?
答案 0 :(得分:4)
我通常建议每个要公开的实体集都有一个Web API控制器。但是,如果您必须将请求真正映射到同一个控制器,请按照我的方式进行操作。定义以下控制器选择器:
public class AnimalControllerSelector : DefaultHttpControllerSelector
{
public override string GetControllerName(HttpRequestMessage request)
{
string controllerName = base.GetControllerName(request);
if (controllerName == "Cats" || controllerName == "Dogs")
{
controllerName = "Animals";
}
return controllerName;
}
}
注册:
config.Services.Replace(typeof(IHttpControllerSelector), new AnimalControllerSelector());
然后使用以下代码访问控制器中的实体集名称:
string entitySetName = (ODataPath.Segments.First() as EntitySetPathSegment).EntitySetName;
希望有所帮助。