我试图在VS 2013中抽象自动生成的ODataController类,因为除了POCO的名称之外,代码看起来是相同的,所以我做了以下操作:
public abstract class ODataControllerBase<T,DB> : ODataController where T : class,IIdentifiable,new() where DB : DbContext,new() { protected DB _DataContext; public ODataControllerBase() : base() { _DataContext = new DB(); } // only one function shown for brevity [Queryable] public SingleResult<T> GetEntity([FromODataUri] int key) { return SingleResult.Create(_DataContext.Set<T>().Where(Entity => Entity.Id.Equals(key))); } }
IIdentifiable是强制T参数具有可读/可写Id整数属性的接口.
实现看起来像这样(POCOs和DataContexts应该已经被创建)
public class MyObjectsController : ODataControllerBase<MyObject,MyDbContext> { public MyObjectsController() : base() { } // That's it - done because all the repetitive code has been abstracted. }
现在,我的WebApiConfig的注册函数只包含以下内容:
public static void Register(HttpConfiguration config) { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); builder.EntitySet<MyObject>("MyObjects"); config.Routes.MapODataRoute("odata","odata",builder.GetEdmModel()); }
我运行的项目,http:// localhost:10000 / odata / MyObjects我得到的响应:
<m:error> <m:code/> <m:message xml:lang="en-US">No HTTP resource was found that matches the request URI `http://localhost:10000/odata/MyObjects.` </m:message> <m:innererror> <m:message>No routing convention was found to select an action for the OData path with template '~/entityset'. </m:message> <m:type/> <m:stacktrace/> </m:innererror> </m:error>
什么不见了?我应该删除什么?这是我们不能做的事情,即我们真的需要直接继承ODataController,而不需要中间的父类?
解决方法
要确定要调用的操作,框架使用路由表. Web API的Visual Studio项目模板创建一个默认路由:
routes.MapHttpRoute( name: "API Default",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional } );
按行动名称路由
使用默认路由模板,Web API使用HTTP方法来选择操作.但是,您也可以创建URI中包含操作名称的路由:
routes.MapHttpRoute( name: "ActionApi",routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional } );
我配置配置如下:
config.Routes.MapHttpRoute( name: "GetMessage",routeTemplate: "api/{controller}/{action}/{quoteName}",defaults: new { quoteName = RouterParameters.Optional } );
访问您的URI,如下所示:
http://localhost:42201/api/Extract/GetMessage/Q3
要么
http://localhost:42201/api/Extract/GetMessage/?quotename=Q3