Skip to content
This repository has been archived by the owner on Dec 29, 2020. It is now read-only.
Trevor Pilley edited this page Mar 25, 2020 · 55 revisions

NuGet version

Net.Http.WebApi.OData is a .NET 4.5 library which uses Net.Http.OData with an implementation for ASP.NET WebApi.

To use it in your own Web API, firstly install the nuget package:

PM> Install-Package Net.Http.WebApi.OData

Configuration

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Wire-up OData and define the Entity Data Model
        config.UseOData(entityDataModelBuilder =>
        {
            entityDataModelBuilder.RegisterEntitySet<Category>("Categories", x => x.Name)
                .RegisterEntitySet<Employee>("Employees", x => x.EmailAddress)
                .RegisterEntitySet<Order>("Orders", x => x.OrderId)
                .RegisterEntitySet<Product>("Products", x => x.Name);
        });

        // Use Attribute Mapping for the OData controllers
        config.MapHttpAttributeRoutes();
    }
}

Note that when you register an Entity Set, you also specify the name of the Entity Set. The name needs to match the URL you intend to use so if you use http://myservice/odata/Products then register the Entity Set using .RegisterEntitySet<Product>("Products", x => x.Name);, if you use http://myservice/odata/Product then register the Entity Set using .RegisterEntitySet<Product>("Product", x => x.Name);.

Getting the OData Query Options

In your controller, define a Get method which accepts a single parameter of ODataQueryOptions:

[RoutePrefix("odata")]
public class ProductsController : ODataController
{
    [HttpGet]
    [Route("Products")]
    public IHttpActionResult Get(ODataQueryOptions queryOptions)
    {
        // Implement query logic.
        var results = ...

        var responseContent = new ODataResponseContent { Value = results };

        if (queryOptions.Count)
        {
            responseContent.Count = results.TotalCount;
        }

        return Ok(responseContent);
    }
}

The ODataQueryOptions class contains properties which can be interrogated to understand the specified query.

See Parsing Query Options in the Net.Http.OData wiki.

Clone this wiki locally