Blog

OData API in ASP.NET Core

– 3 Minutes

Microsoft is making it incredibly easy to create an OData API using ASP.NET Core.  All you have to do is create an ASP.NET Core project, add an ODataController and add some boilerplate code.

First, create a new ASP.NET Core Web Application project in Visual Studio -- choose the Empty template.  After it's been added to your solution, add the Nuget package Microsoft.AspNetCore.OData.  You may need to include prerelease packages (as of right now it's v7.0.0-beta2).

Let's create a model called Product.

namespace BGuidinger.Samples
{
    public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}

We'll also create a very simple controller for it.

namespace BGuidinger.Samples
{
    using Microsoft.AspNet.OData;
    using Microsoft.AspNetCore.Mvc;
    using System.Collections.Generic;
    using System.Linq;

    public class ProductsController : ODataController
    {
        private List _products = new List()
        {
            new Product() { ID = 1, Name = "Product ABC" },
            new Product() { ID = 2, Name = "Product XYZ" },
        };

        [EnableQuery]
        public IActionResult Get()
        {
            return Ok(_products.AsQueryable());
        }
    }
}

Note that you have to set the EnableQuery attribute and return an IQueryable for the $filter/$select query options to work.

Now, let's wire it up in our Startup.cs file and hit F5.

namespace BGuidinger.Samples
{
    using Microsoft.AspNet.OData.Builder;
    using Microsoft.AspNet.OData.Extensions;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.DependencyInjection;

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOData();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet("Products");
            
            var model = builder.GetEdmModel();

            app.UseMvc(route =>
            {
                route.Select().Filter().Expand().OrderBy().Count().MaxTop(null);
                route.MapODataServiceRoute("odata", null, model);
            });
        }
    }
}

When we debug and run it, you'll see that we can query the API as a standards-compliant OData API!

OData Filter Select

Being able to easily create an OData API opens up all sorts of possibilities.  For example, we can easily create a web service that surfaces on-premises data as a Virtual Entity in Dynamics 365.

Comments

No comments.