"
 
 
 
ASP.NET (snapshot 2017) Microsoft documentation and samples

Creating an OData v3 Endpoint with Web API 2

by Mike Wasson

Download Completed Project

The Open Data Protocol (OData) is a data access protocol for the web. OData provides a uniform way to structure data, query the data, and manipulate the data set through CRUD operations (create, read, update, and delete). OData supports both AtomPub (XML) and JSON formats. OData also defines a way to expose metadata about the data. Clients can use the metadata to discover the type information and relationships for the data set.

ASP.NET Web API makes it easy to create an OData endpoint for a data set. You can control exactly which OData operations the endpoint supports. You can host multiple OData endpoints, alongside non-OData endpoints. You have full control over your data model, back-end business logic, and data layer.

Software versions used in the tutorial

Web API OData support was added in ASP.NET and Web Tools 2012.2 Update. However, this tutorial uses scaffolding that was added in Visual Studio 2013.

In this tutorial, you will create a simple OData endpoint that clients can query. You will also create a C# client for the endpoint. After you complete this tutorial, the next set of tutorials show how to add more functionality, including entity relations, actions, and expand/select.

## Create the Visual Studio Project

In this tutorial, you will create an OData endpoint that supports basic CRUD operations. The endpoint will expose a single resource, a list of products. Later tutorials will add more features.

Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project.

In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. Select the ASP.NET Web Application template.

In the New ASP.NET Project dialog, select the Empty template. Under “Add folders and core references for…”, check Web API. Click OK.

## Add an Entity Model

A model is an object that represents the data in your application. For this tutorial, we need a model that represents a product. The model corresponds to our OData entity type.

In Solution Explorer, right-click the Models folder. From the context menu, select Add then select Class.

In the Add New Item dialog, name the class “Product”.

[!NOTE] By convention, model classes are placed in the Models folder. You don’t have to follow this convention in your own projects, but we’ll use it for this tutorial.

In the Product.cs file, add the following class definition:

[!code-csharpMain]

   1:  public class Product
   2:  {
   3:      public int ID { get; set; }
   4:      public string Name { get; set; }
   5:      public decimal Price { get; set; }
   6:      public string Category { get; set; }
   7:  }

The ID property will be the entity key. Clients can query products by ID. This field would also be the primary key in the back-end database.

Build the project now. In the next step, we’ll use some Visual Studio scaffolding that uses reflection to find the Product type.

## Add an OData Controller

A controller is a class that handles HTTP requests. You define a separate controller for each entity set in you OData service. In this tutorial, we’ll create a single controller.

In Solution Explorer, right-click the the Controllers folder. Select Add and then select Controller.

In the Add Scaffold dialog, select “Web API 2 OData Controller with actions, using Entity Framework”.

In the Add Controller dialog, name the controller “ProductsController”. Select the “Use async controller actions” checkbox. In the Model drop-down list, select the Product class.

Click the New data context… button. Leave the default name for the data context type, and click Add.

Click Add in the Add Controller dialog to add the controller.

Note: If you get an error message that says “There was an error getting the type…”, make sure that you built the Visual Studio project after you added the Product class. The scaffolding uses reflection to find the class.

The scaffolding adds two code files to the project:

## Add the EDM and Route

In Solution Explorer, expand the App_Start folder and open the file named WebApiConfig.cs. This class holds configuration code for Web API. Replace this code with the following:

[!code-csharpMain]

   1:  using ProductService.Models;
   2:  using System.Web.Http;
   3:  using System.Web.Http.OData.Builder;
   4:   
   5:  namespace ProductService
   6:  {
   7:      public static class WebApiConfig
   8:      {
   9:          public static void Register(HttpConfiguration config)
  10:          {
  11:              ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
  12:              builder.EntitySet<Product>("Products");
  13:              config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
  14:          }
  15:      }
  16:  }

This code does two things:

An EDM is an abstract model of the data. The EDM is used to create the metadata document and define the URIs for the service. The ODataConventionModelBuilder creates an EDM by using a set of default naming conventions EDM. This approach requires the least code. If you want more control over the EDM, you can use the ODataModelBuilder class to create the EDM by adding properties, keys, and navigation properties explicitly.

The EntitySet method adds an entity set to the EDM:

[!code-csharpMain]

   1:  modelBuilder.EntitySet<Product>("Products");

The string “Products” defines the name of the entity set. The name of the controller must match the name of the entity set. In this tutorial, the entity set is named “Products” and the controller is named ProductsController. If you named the entity set “ProductSet”, you would name the controller ProductSetController. Note that an endpoint can have multiple entity sets. Call EntitySet<T> for each entity set, and then define a corresponding controller.

The MapODataRoute method adds a route for the OData endpoint.

[!code-csharpMain]

   1:  config.Routes.MapODataRoute("ODataRoute", "odata", model);

The first parameter is a friendly name for the route. Clients of your service do not see this name. The second parameter is the URI prefix for the endpoint. Given this code, the URI for the Products entity set is http://hostname/odata/Products. Your application can have more than one OData endpoint. For each endpoint, call MapODataRoute and provide a unique route name and a unique URI prefix.

## Seed the Database (Optional)

In this step, you will use Entity Framework to seed the database with some test data. This step is optional, but it lets you test out your OData endpoint right away.

From the Tools menu, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, enter the following command:

[!code-consoleMain]

   1:  Enable-Migrations

This adds a folder named Migrations and a code file named Configuration.cs.

Open this file and add the following code to the Configuration.Seed method.

[!code-csharpMain]

   1:  protected override void Seed(ProductService.Models.ProductServiceContext context)
   2:  {
   3:      // New code 
   4:      context.Products.AddOrUpdate(new Product[] {
   5:          new Product() { ID = 1, Name = "Hat", Price = 15, Category = "Apparel" },
   6:          new Product() { ID = 2, Name = "Socks", Price = 5, Category = "Apparel" },
   7:          new Product() { ID = 3, Name = "Scarf", Price = 12, Category = "Apparel" },
   8:          new Product() { ID = 4, Name = "Yo-yo", Price = 4.95M, Category = "Toys" },
   9:          new Product() { ID = 5, Name = "Puzzle", Price = 8, Category = "Toys" },
  10:      });
  11:  }

In the Package Manager Console Window, enter the following commands:

[!code-consoleMain]

   1:  Add-Migration Initial
   2:  Update-Database

These commands generate code that creates the database, and then executes that code.

## Exploring the OData Endpoint

In this section, we’ll use the Fiddler Web Debugging Proxy to send requests to the endpoint and examine the response messages. This will help you to understand the capabilities of an OData endpoint.

In Visual Studio, press F5 to start debugging. By default, Visual Studio opens your browser to http://localhost:*port*, where port is the port number configured in the project settings.

You can change the port number in the project settings. In Solution Explorer, right-click the project and select Properties. In the properties window, select Web. Enter the port number under Project Url.

Service Document

The service document contains a list of the entity sets for the OData endpoint. To get the service document, send a GET request to the root URI of the service.

Using Fiddler, enter the following URI in the Composer tab: http://localhost:port/odata/, where port is the port number.

Click the Execute button. Fiddler sends an HTTP GET request to your application. You should see the response in the Web Sessions list. If everything is working, the status code will be 200.

Double-click the response in the Web Sessions list to see the details of the response message in the Inspectors tab.

The raw HTTP response message should look similar to the following:

[!code-consoleMain]

   1:  HTTP/1.1 200 OK
   2:  Cache-Control: no-cache
   3:  Pragma: no-cache
   4:  Content-Type: application/atomsvc+xml; charset=utf-8
   5:  Expires: -1
   6:  Server: Microsoft-IIS/8.0
   7:  DataServiceVersion: 3.0
   8:  Date: Mon, 23 Sep 2013 17:51:01 GMT
   9:  Content-Length: 364
  10:   
  11:  <?xml version="1.0" encoding="utf-8"?>
  12:  <service xml:base="http://localhost:60868/odata" 
  13:      xmlns="http://www.w3.org/2007/app" xmlns:atom="http://www.w3.org/2005/Atom">
  14:    <workspace>
  15:      <atom:title type="text">Default</atom:title>
  16:      <collection href="Products">
  17:          <atom:title type="text">Products</atom:title>
  18:      </collection>
  19:      </workspace>
  20:  </service></pre>

By default, Web API returns the service document in AtomPub format. To request JSON, add the following header to the HTTP request:

Accept: application/json

Now the HTTP response contains a JSON payload:

[!code-consoleMain]

   1:  HTTP/1.1 200 OK
   2:  Cache-Control: no-cache
   3:  Pragma: no-cache
   4:  Content-Type: application/json; charset=utf-8
   5:  Expires: -1
   6:  Server: Microsoft-IIS/8.0
   7:  DataServiceVersion: 3.0
   8:  Date: Mon, 23 Sep 2013 22:59:28 GMT
   9:  Content-Length: 136
  10:   
  11:  {
  12:    "odata.metadata":"http://localhost:60868/odata/$metadata","value":[
  13:      {
  14:        "name":"Products","url":"Products"
  15:      }
  16:    ]
  17:  }

Service Metadata Document

The service metadata document describes the data model of the service, using an XML language called the Conceptual Schema Definition Language (CSDL). The metadata document shows the structure of the data in the service, and can be used to generate client code.

To get the metadata document, send a GET request to http://localhost:port/odata/$metadata. Here is the metadata for the endpoint shown in this tutorial.

[!code-consoleMain]

   1:  HTTP/1.1 200 OK
   2:  Cache-Control: no-cache
   3:  Pragma: no-cache
   4:  Content-Type: application/xml; charset=utf-8
   5:  Expires: -1
   6:  Server: Microsoft-IIS/8.0
   7:  DataServiceVersion: 3.0
   8:  Date: Mon, 23 Sep 2013 23:05:52 GMT
   9:  Content-Length: 1086
  10:   
  11:  <?xml version="1.0" encoding="utf-8"?>
  12:  <edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
  13:    <edmx:DataServices m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0" 
  14:      xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  15:      <Schema Namespace="ProductService.Models" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
  16:        <EntityType Name="Product">
  17:          <Key>
  18:            <PropertyRef Name="ID" />
  19:          </Key>
  20:          <Property Name="ID" Type="Edm.Int32" Nullable="false" />
  21:          <Property Name="Name" Type="Edm.String" />
  22:          <Property Name="Price" Type="Edm.Decimal" Nullable="false" />
  23:          <Property Name="Category" Type="Edm.String" />
  24:        </EntityType>
  25:      </Schema>
  26:      <Schema Namespace="Default" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
  27:        <EntityContainer Name="Container" m:IsDefaultEntityContainer="true">
  28:          <EntitySet Name="Products" EntityType="ProductService.Models.Product" />
  29:        </EntityContainer>
  30:      </Schema>
  31:    </edmx:DataServices>
  32:  </edmx:Edmx>

Entity Set

To get the Products entity set, send a GET request to http://localhost:port/odata/Products.

[!code-consoleMain]

   1:  HTTP/1.1 200 OK
   2:  Cache-Control: no-cache
   3:  Pragma: no-cache
   4:  Content-Type: application/json; charset=utf-8
   5:  Expires: -1
   6:  Server: Microsoft-IIS/8.0
   7:  DataServiceVersion: 3.0
   8:  Date: Mon, 23 Sep 2013 23:01:31 GMT
   9:  Content-Length: 459
  10:   
  11:  {
  12:    "odata.metadata":"http://localhost:60868/odata/$metadata#Products","value":[
  13:      {
  14:        "ID":1,"Name":"Hat","Price":"15.00","Category":"Apparel"
  15:      },{
  16:        "ID":2,"Name":"Socks","Price":"5.00","Category":"Apparel"
  17:      },{
  18:        "ID":3,"Name":"Scarf","Price":"12.00","Category":"Apparel"
  19:      },{
  20:        "ID":4,"Name":"Yo-yo","Price":"4.95","Category":"Toys"
  21:      },{
  22:        "ID":5,"Name":"Puzzle","Price":"8.00","Category":"Toys"
  23:      }
  24:    ]
  25:  }

Entity

To get an individual product, send a GET request to http://localhost:port/odata/Products(1), where “1” is the product ID.

[!code-consoleMain]

   1:  HTTP/1.1 200 OK
   2:  Cache-Control: no-cache
   3:  Pragma: no-cache
   4:  Content-Type: application/json; charset=utf-8
   5:  Expires: -1
   6:  Server: Microsoft-IIS/8.0
   7:  DataServiceVersion: 3.0
   8:  Date: Mon, 23 Sep 2013 23:04:29 GMT
   9:  Content-Length: 140
  10:   
  11:  {
  12:    "odata.metadata":"http://localhost:60868/odata/$metadata#Products/@Element","ID":1,
  13:        "Name":"Hat","Price":"15.00","Category":"Apparel"
  14:  }

## OData Serialization Formats

OData supports several serialization formats:

By default, Web API uses AtomPubJSON “light” format.

To get AtomPub format, set the Accept header to “application/atom+xml”. Here is an example response body:

[!code-consoleMain]

   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <entry xml:base="http://localhost:60868/odata" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml">
   3:    <id>http://localhost:60868/odata/Products(1)</id>
   4:    <category term="ProductService.Models.Product" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
   5:    <link rel="edit" href="http://localhost:60868/odata/Products(1)" />
   6:    <link rel="self" href="http://localhost:60868/odata/Products(1)" />
   7:    <title />
   8:    <updated>2013-09-23T23:42:11Z</updated>
   9:    <author>
  10:      <name />
  11:    </author>
  12:    <content type="application/xml">
  13:      <m:properties>
  14:        <d:ID m:type="Edm.Int32">1</d:ID>
  15:        <d:Name>Hat</d:Name>
  16:        <d:Price m:type="Edm.Decimal">15.00</d:Price>
  17:        <d:Category>Apparel</d:Category>
  18:      </m:properties>
  19:    </content>
  20:  </entry>

You can see one obvious disadvantage of the Atom format: It’s a lot more verbose than the JSON light. However, if you have a client that understands AtomPub, the client might prefer that format over JSON.

Here is the JSON light version of the same entity:

[!code-consoleMain]

   1:  {
   2:    "odata.metadata":"http://localhost:60868/odata/$metadata#Products/@Element",
   3:    "ID":1,
   4:    "Name":"Hat",
   5:    "Price":"15.00",
   6:    "Category":"Apparel"
   7:  }

The JSON light format was introduced in version 3 of the OData protocol. For backward compatibility, a client can request the older “verbose” JSON format. To request verbose JSON, set the Accept header to application/json;odata=verbose. Here is the verbose version:

[!code-consoleMain]

   1:  {
   2:    "d":{
   3:      "__metadata":{
   4:        "id":"http://localhost:18285/odata/Products(1)",
   5:        "uri":"http://localhost:18285/odata/Products(1)",
   6:        "type":"ProductService.Models.Product"
   7:      },"ID":1,"Name":"Hat","Price":"15.00","Category":"Apparel"
   8:    }
   9:  }

This format conveys more metadata in the response body, which can add considerable overhead over an entire session. Also, it adds a level of indirection by wrapping the object in a property named “d”.

Next Steps





Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v3/creating-an-odata-endpoint.htm
<SITEMAP>  <MVC>  <ASP>  <NET>  <DATA>  <KIOSK>  <FLEX>  <SQL>  <NOTES>  <LINUX>  <MONO>  <FREEWARE>  <DOCS>  <ENG>  <CHAT ME>  <ABOUT ME>  < THANKS ME>