Dilshod K
Dilshod K

Reputation: 3032

OData custom routing conventions in different controllers

I got some examples of routing conventions from

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

In this example, I can get properties of the entity using this query /odata/Products(1)/Suppliers

I want to put two parameters in Products. For example /odata/Products(1,2)/Suppliers How can I setup this?

Here is CustomRoutingConvention class:

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 config class:

 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);

    }
}

Upvotes: 2

Views: 904

Answers (1)

OData does not allow you to do this. You can create function for this: OData Actions and Functions

Upvotes: 1

Related Questions