ASP.NET WebAPI: Generic controller for OData endpoint

后端 未结 2 1462
[愿得一人]
[愿得一人] 2021-02-04 14:20

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 h

相关标签:
2条回答
  • 2021-02-04 14:54

    I came up against the same problem, and ended up writing a custom IHttpControllerSelector instead of an IODataRoutingConvention. IODataRoutingConvention looks like a good option if your generic controller doesn't require generics :) . But since IODataRoutingConvention.SelectController() only returns a string, I don't see how it will work for instantiating a controller with generic type parameters.

    I decided this problem needs a good, general-purpose, open-source solution - so I created one: https://github.com/EntityRepository/ODataServer . It's prerelease now, but I'm currently doing a lot of work on it. I think there's more to it than just choosing the right controller, there are general patterns to define for shared controllers, and by default Web API OData expects strongly typed and strongly named navigation properties which makes it challenging to create a re-usable implementation.

    0 讨论(0)
  • 2021-02-04 15:11

    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";
        }
    }
    

    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);
    
    0 讨论(0)
提交回复
热议问题