Create a C# Client for the OData Endpoint
In this section, we’ll write a C# client that calls the OData service we created. The client will use WCF Data Services to create a proxy class for the OData service.
In Visual Studio, create a new console application. Keep the Web API project open in another instance of Visual Studio, because we need it to run the OData service. (For this tutorial we are not deploying the service, so we just run it from Visual Studio.)
Add a Service Reference
- Install WCF Data Services 5.2 Tools.
- Start the OData service by running the Web API project in Visual Studio.
- In the console application, go to Solution Explorer, right-click the project, and select Add Service Reference.
- In the Add Service Reference dialog, enter the root URI for the OData service, http://localhost:port/odata/. (The root URI is whatever you defined in the MapODataRoute method. See Configure the Endpoint.)
- Enter a namespace for the proxy class.
- Click Go.
- After the wizard finds the service, click OK.
The Add Service Reference wizard creates a proxy class for the OData service by retrieving the service metadata document.
Query the Service
Open the Program.cs file. Inside the Main
function, reate a new instance of the proxy class:
var container = new ProductsService.Container( new Uri("http://localhost:18285/odata/"));
Add an event handler that prints the request URIs to the console window. (This step isn’t required, but it’s interesting to see the URIs for each query.)
container.SendingRequest2 += (s, e) => { Console.WriteLine("{0} {1}", e.RequestMessage.Method, e.RequestMessage.Url); };
To get the list of all products, simply enumerate the container.Products
collection:
// Get all products foreach (var product in container.Products) { Console.WriteLine("{0} {1} {2}", product.Name, product.Price, product.Category); }
To query for a product by ID, use a LINQ expression:
// Select products var products = from p in container.Products where p.ID == 1 select p; var product1 = products.FirstOrDefault(); if (product1 != null) { Console.WriteLine("{0} {1} {2}", product1.Name, product1.Price, product1.Category); }
When you run the application, the output should look like this. Remember to keep the Web API project running, so that the client can query it.
GET http://localhost:18285/odata/Products Hat 15 Apparel Socks 5 Apparel Scarf 12 Apparel Yo-yo 4.95 Toys Puzzle 8 Toys GET http://localhost:18285/odata/Products(1) Hat 15 Apparel
Comments (0) RSS Feed