不同控制器中的OData自定义路由约定

时间:2020-04-24 08:36:41

标签: c# routes odata

我从

获得了一些路由约定的示例

https://docs.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-routing-conventions

在此示例中,我可以使用此查询/odata/Products(1)/Suppliers

获取实体的属性

我想在“产品”中添加两个参数。例如/odata/Products(1,2)/Suppliers 我该如何设置?

这是CustomRoutingConvention类:

public class NavigationIndexRoutingConvention : EntitySetRoutingConvention
{
    public override string SelectAction(ODataPath odataPath, HttpControllerContext context, 
        ILookup<string, HttpActionDescriptor> actionMap)
    {
        if (context.Request.Method == HttpMethod.Get && 
            odataPath.PathTemplate == "~/entityset/key/navigation/key")
        {
            NavigationPathSegment navigationSegment = odataPath.Segments[2] as NavigationPathSegment;
            IEdmNavigationProperty navigationProperty = navigationSegment.NavigationProperty.Partner;
            IEdmEntityType declaringType = navigationProperty.DeclaringType as IEdmEntityType;

            string actionName = "Get" + declaringType.Name;
            if (actionMap.Contains(actionName))
            {
                // Add keys to route data, so they will bind to action parameters.
                KeyValuePathSegment keyValueSegment = odataPath.Segments[1] as KeyValuePathSegment;
                context.RouteData.Values[ODataRouteConstants.Key] = keyValueSegment.Value;

                KeyValuePathSegment relatedKeySegment = odataPath.Segments[3] as KeyValuePathSegment;
                context.RouteData.Values[ODataRouteConstants.RelatedKey] = relatedKeySegment.Value;

                return actionName;
            }
        }
        // Not a match.
        return null;
    }
}

Web api配置类:

 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
        // Create EDM (not shown).

        // Create the default collection of built-in conventions.
        var conventions = ODataRoutingConventions.CreateDefault();
        // Insert the custom convention at the start of the collection.
        conventions.Insert(0, new NavigationIndexRoutingConvention());

        config.Routes.MapODataRoute(routeName: "ODataRoute",
            routePrefix: "odata",
            model: modelBuilder.GetEdmModel(),
            pathHandler: new DefaultODataPathHandler(),
            routingConventions: conventions);

    }
}

1 个答案:

答案 0 :(得分:2)

OData不允许您执行此操作。您可以为此创建函数:OData Actions and Functions