How to dynamically add OData Web Api routes *after* Application_Start?

谁都会走 提交于 2019-12-04 16:36:35

Well, I spent some time with the good folks over at MSDN and got an answer!

Here's the way the Orders entity route needs to be registered:

var builder = new ODataConventionModelBuilder();
builder.EntitySet<Order>("Orders");

var route = config.Routes.Where(r => r is System.Web.OData.Routing.ODataRoute).First();
var odataRoute = route as System.Web.OData.Routing.ODataRoute;

config.MapODataServiceRoute(
    routeName: "OrdersRoute", 
    routePrefix: "odata", 
    model: builder.GetEdmModel(),
    pathHandler: odataRoute.PathRouteConstraint.PathHandler,
    routingConventions: odataRoute.PathRouteConstraint.RoutingConventions);

Nice. Now .../odata/Orders can be accessed no problem.

As we talked in the comment, multiple entities of the same route:

public static void Register(HttpConfiguration config)
{
    var builder = new ODataConventionModelBuilder();
    builder.EntitySet<Product>("Products");
    builder.EntitySet<Order>("Orders");
    config.MapODataServiceRoute(routeName: "OData", routePrefix: "odata", model: builder.GetEdmModel());
}

Then you can issue both requests:

1. http:///odata/Products and 
2. http:///odata/Orders
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!