ASP.NET WebAPI: Generic controller for OData endpoint

后端 未结 2 1461
[愿得一人]
[愿得一人] 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 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 actionMap)
        {
            return null;
        }
    
        public string SelectController(ODataPath odataPath, HttpRequestMessage request)
        {
            return "SomeFixedContrllerNameWithoutTheControllerSuffix";
        }
    }
    

    You can register that routing convention using the following code,

    IList routingConventions = ODataRoutingConventions.CreateDefault();
    routingConventions.Insert(0, new CustomControllerRoutingConvention());
    config.Routes.MapODataRoute("OData", "odata", builder.GetEdmModel(), new DefaultODataPathHandler(), routingConventions);
    

提交回复
热议问题