ASP.NET的WebAPI:为端点OData的通用控制器 [英] ASP.NET WebAPI: Generic controller for OData endpoint
问题描述
我目前在ASP.NET MVC 4的Web API的OData端点实验。我喜欢这个概念,并尝试拿出有效的方法在我们的项目中使用它。
我有一个问题是:我们有一个服务,它能够返回一个IQueryable和输入需要一个实体的名称:
I'm currently experimenting with OData endpoints in ASP.NET MVC 4 Web API. I like the concept and try to come up with efficient ways to use it in our project. One question I have is the following: we have a service that is able to return an IQueryable and takes the name of an entity as Input:
public IQueryable GetAll(string entityName);
在标准的Web API(相对于OData的控制器),我可以创建一个通用的控制器,可以在表格/ API /实体/ {entityName}的调用和返回的IQueryable。
在OData的控制器的情况下,我开展以下特定实体步骤:
In standard Web API (as opposed to OData Controllers) I can create a generic controller, that can be called in the form /api/entities/{entityName} and returns the IQueryable. In case of an OData Controller, I carry out the following entity-specific steps:
- 注册的实体模型。
- 创建的,从EntitySetController&LT得出每个实体单独的控制器;>
我要使用的一般性服务和避免之多特定实体的实现成为可能。如果服务可以返回实体和相应的类型的列表的第一个步骤可以很容易地实现自动化。
这使得第2步,因为到现在我需要为每个实体特定的控制器。我也想避免这一点,创建一个使用通用服务的通用控制器。
I want to use the generic service and avoid as much entity-specific implementations as possible. The first step can easily be automated if the service can return a list of the entities and the corresponding types. That leaves step 2, because up to now I need to create a specific controller for each entity. I also want to avoid that and create a generic controller that uses the generic service.
谁能推荐一个解决方案,可能通过影响OData的路由?
Can anyone recommend a solution, maybe by influencing OData routing?
推荐答案
您可以创建一个选择相同的控制器无论实体集是一个自定义的路由规则。例如,
You can create a custom routing convention that selects the same controller no matter what the entity set is. Example,
public class CustomControllerRoutingConvention : IODataRoutingConvention
{
public string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
{
return null;
}
public string SelectController(ODataPath odataPath, HttpRequestMessage request)
{
return "SomeFixedContrllerNameWithoutTheControllerSuffix";
}
}
您可以使用以下code寄存器路由约定,
You can register that routing convention using the following code,
IList<IODataRoutingConvention> routingConventions = ODataRoutingConventions.CreateDefault();
routingConventions.Insert(0, new CustomControllerRoutingConvention());
config.Routes.MapODataRoute("OData", "odata", builder.GetEdmModel(), new DefaultODataPathHandler(), routingConventions);
这篇关于ASP.NET的WebAPI:为端点OData的通用控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!