Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure OData end point in a self-hosted Web API application

I'm building an OWIN self-hosted Web API 2 service. I need for this service to expose OData end points.

The traditional IIS-hosted method involves App_Start/WebApiConfig.cs:

using ProductService.Models;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // New code:
        ODataModelBuilder builder = new ODataConventionModelBuilder();
        builder.EntitySet<Product>("Products");
        config.MapODataServiceRoute(
            routeName: "ODataRoute",
            routePrefix: null,
            model: builder.GetEdmModel());
    }
}

However, in my self-hosted solution there is no such thing as WebApiConfig.cs

Where and how can I specify this OData configuration?

like image 445
Eugene Goldberg Avatar asked May 01 '15 03:05

Eugene Goldberg


People also ask

How do I enable OData in Web API?

Right click on the Controllers folder > Add > Controller> selecting Web API 2 OData v3 Controller with actions, using Entity Framework > click Add. After clicking on Add button, window will pop up, as shown below. We need to specify our Model class (in this case Employee. cs) and name for our Controller.

What is OData in Web API with example?

The Open Data Protocol (OData) is a data access protocol for the web. OData provides a uniform way to query and manipulate data sets through CRUD operations (create, read, update, and delete). ASP.NET Web API supports both v3 and v4 of the protocol.


1 Answers

You're correct, there isn't necessarily such a thing as WebApiConfig.cs in a self-hosted OWIN project since you declare the middleware you need as you need it. However, if you're following OWIN self-hosting tutorials, you've probably bumped into the Startup.cs concept, which is what you can use, since you can instantiate your HttpConfiguration there.

public class Startup 
{ 
    public void Configuration(IAppBuilder appBuilder) 
    { 
        // Configure Web API for self-host. 
        HttpConfiguration config = new HttpConfiguration(); 
        config.Routes.MapHttpRoute( 
            name: "DefaultApi", 
            routeTemplate: "api/{controller}/{id}", 
            defaults: new { id = RouteParameter.Optional } 
        );  

        ODataModelBuilder builder = new ODataConventionModelBuilder();
        builder.EntitySet<Product>("Products");
        config.MapODataServiceRoute(
        routeName: "ODataRoute",
        routePrefix: null,
        model: builder.GetEdmModel());

        appBuilder.UseWebApi(config);
    } 
} 
like image 88
David L Avatar answered Oct 08 '22 15:10

David L