A lot of developers have asked me recently about OData compatibility with ASP.NET Core 3.0 and again with .NET Core 3.1 after it’s very recent release.
This demand became more and more critical with the recent announcement from the .NET team around .NET Core 2.2 reaching the end of its life on Dec 23rd of this year.
And because of all of that, the OData team at Microsoft have been working diligently in the last few months to ensure a stable release of OData that supports .NET Core 3.1 makes it out to the public as soon as possible.
And while the final release might take a bit longer to be production-ready, the OData team has recently released a beta version for developers to experiment with it, learn about it’s capabilities and possibly build some demo APIs and leverage it in some POCs.
In this article, I’m going to show you how you can build a modern ASP.NET Core 3.1 API with OData by simply following very few simple steps.
Prerequisites
In order for you to be able to create this demo on your local machine, you want to make sure that you have Visual Studio 2019 version 16.4 or later so you can leverage the capabilities of .NET Core 3.1, if you install that particular version of VS 2019 you will not need to install .NET Core 3.1 separately as it comes with the bundle.
You can check the current version of your Visual Studio 2019 by going to top menu, then Help then About Visual Studio as shows in the following screenshots:
If your current version of Visual Studio 2019 is lower than 16.4, you can upgrade your Visual Studio instance by clicking on the bell icon at the lower right corner of your Visual Studio instance then selecting to upgrade your Visual Studio as shows in the following screenshots:
Once you click the “More Details” link, it usually takes about 10 seconds and then you should be prompt with a dialog to upgrade your Visual Studio instance as follows:
Please make sure you save all your work before you click the “Update” button as the process will require Visual Studio to close automatically, you will not be prompted to save your work before Visual Studio closes, you also want to make sure you have Admin permissions to be able to continue with that process.
Once the upgrade is done, now you are ready to build ASP.NET Core applications with .NET Core 3.1, let’s talk about setting your project up.
Setting Things Up
For starters, let’s create a new ASP.NET Core Web Application by either starting a new instance of Visual Studio or simply going to File -> New -> Project, you should be then prompted with the following dialog:
After selecting ASP.NET Core Web Application (with C#) click the Next button you will be prompted to create a new name for your project and then selecting the version and template of which your project should be based on as follows:
Please make sure you select ASP.NET Core 3.1 from the drop down menu at the top right side, and API as a template for your project then click “Create“.
Installing OData
Now that you have created a new project, let’s go ahead and install the beta release of OData for ASP.NET Core 3.1
There are two ways you can install the beta library depends on your preference, if you are a command line kind of developer, you can simply open the package manager console by clicking on the Tools top menu option, then Nuget Package Manager then Package Manager Console as follows:
you will be prompted with a console window so you can type the following command:
PM> Install-Package Microsoft.AspNetCore.OData -Version 7.3.0-beta
If you don’t like using command lines, you can simply install the very same package by going to the exact same menu options we selected above, except you are going to choose Manage Nuget Packages for Solution instead of Package Manager Console the following dialog will appear so you can install the library as follows:
There are few things that I have highlighted in that screenshot that you need to pay attention to:
- You must check the “Include prerelease” so you can see the beta release of the nuget package.
- Search for Microsoft.AspNetCore.OData and select the first option.
- Select the project in which you want to install your library, in our case here since we have one project, it’s safe to just check the entire project.
- Make sure you select Latest prerelease 7.3.0-beta in the drop down menu on the right side before you click the Install button.
Models & Controllers
Now that we have OData installed, let’s create a Student model and create a controller to return a list of students as follows:
using System; namespace ODataCore3BetaAPI.Models { public class Student { public Guid Id { get; set; } public string Name { get; set; } public int Score { get; set; } } }
Now let’s create a simple API controller that returns a list of students:
using System; using System.Collections.Generic; using Microsoft.AspNet.OData; using Microsoft.AspNetCore.Mvc; using ODataCore3BetaAPI.Models; namespace ODataCore3BetaAPI.Controllers { public class StudentsController : ControllerBase { [HttpGet] [EnableQuery()] public IEnumerable<Student> Get() { return new List<Student> { CreateNewStudent("Cody Allen", 130), CreateNewStudent("Todd Ostermeier", 160), CreateNewStudent("Viral Pandya", 140) }; } private static Student CreateNewStudent(string name, int score) { return new Student { Id = Guid.NewGuid(), Name = name, Score = score }; } } }
Please notice that this controller is only created this way for a demo purpose, ideally your controller should return an IQueryable to achieve better performance and execute queries on your database server if you are retrieving your data from a database.
Final Step
Our final step here is to modify the startup.cs file to support OData, our code here will be very similar to our code from previous articles, let’s start with the ConfigureServices method in our startup.cs file as follows:
public void ConfigureServices(IServiceCollection services) { services.AddControllers(mvcOptions => mvcOptions.EnableEndpointRouting = false); services.AddOData(); }
You will notice a couple of changes in the above code, Adding OData which is just as similar as any other OData powered application.
The second change is disabling endpoint routing, let’s talk about that for a bit.
For starters, this is not an ideal situation, the final release of OData shall allow endpoint routing while supporting OData queries.
But for those who want to understand what endpoint routing setting is, especially for .NET Core 3.0 and above, here’s a quote from a previous post for Daniel Roth:
In ASP.NET Core 2.2 we introduced a new routing implementation called Endpoint Routing which replacesÂ
IRouter
-based routing for ASP.NET Core MVC. In the upcoming 3.0 release Endpoint Routing will become central to the ASP.NET Core middleware programming model. Endpoint Routing is designed to support greater interoperability between frameworks that need routing (MVC, gRPC, SignalR, and more …) and middleware that want to understand the decisions made by routing (localization, authorization, CORS, and more …).While it’s still possible to use the oldÂ
UseMvc()
 orÂUseRouter()
 middleware in a 3.0 application, we recommend that every application migrate to Endpoint Routing if possible. We are taking steps to address compatibility bugs and fill in previously unsupported scenarios. We welcome your feedback about what features are missing or anything else that’s not great about routing in this preview release.
And while endpoint routing is one of the most important upgrades to ASP.NET Core 3.0, with this beta release you could still leverage the power of OData without leveraging endpoint routing temporarily.
With that being said, let’s move on to the next step which is implementing a GetEdmModel method as we have done previously and change the routing implementing in the Configure method as follows:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseMvc(routeBuilder => { routeBuilder.Select().Filter(); routeBuilder.MapODataServiceRoute("odata", "odata", GetEdmModel()); }); //app.UseEndpoints(endpoints => //{ // endpoints.MapControllers(); //}); } IEdmModel GetEdmModel() { var odataBuilder = new ODataConventionModelBuilder(); odataBuilder.EntitySet<Student>("Students"); return odataBuilder.GetEdmModel(); }
I have intentionally left the app.UseEndPoints to show you what code you need to remove (again, temporarily for this beta release) and what code you need to add to leverage the power of OData. And that should be the final step in this tutorial, now you can run you application and call your endpoint as follows:
https://localhost:44344/odata/students?$select=name
and the results should be as follows:
{ "@odata.context": "https://localhost:44344/odata/$metadata#Students(Name)", "value": [ { "Name": "Cody Allen" }, { "Name": "Todd Ostermeier" }, { "Name": "Viral Pandya" } ] }
Final Notes
- Huge thanks to Sam Xu, Saurabh Madan and the the rest of the OData team on the great efforts they have made to produce this beta release, and as you are reading this article, the team continues to push improvements and features before announcing the final release of OData 7.3.0 for ASP.NET Core 3.1 which should have a long term support of 3 years.
- This beta release should not be used in any way shape or form for production environments, it’s mainly for POCs and demos.
- OData team should announce the final release of OData for .NET Core 3.1 sometime in the second quarter of 2020.
- You can follow up on the most recent updates for OData on this public github repository and this thread as well.
- This is a repository for the demo in this article.
If you have any questions, comments, concerns or if you are running into any issues running this demo feel free to reach out on this blog post, we are more than happy to listen to your feedback and communicate your concerns.
Update
- Just a couple of days ago, OData team has released the final version of OData 7.3.0 to support .NET Core 3.1 you can find the package in here.
- OData team is working very closely with the .NET team to address the endpoint routing issue, we will announce the changes as soon as they become ready.
- You can now use OData in your production environment as it passed it’s beta stage and is now ready for production-ready applications.
How can i remove @odata.context from response. Need to restrict access to view $metadata.
Thanks for your great article,
I’m currently facing a problem, I am using OData with EF Core and AutoMapper and I already have the queries executed using projection, however when I use expand I only get the “[” symbol.
If you could help me or make an example would be great.
Thank you very much.
Hi,
When will be Endpoint routing available? We want to use OData for an open source project but we need Endpoint routing integration.
Regards!
this blob post uses the web api controller base, but when i look at
Odata Webapi Sample
it does not, it uses OData Controller -- so which one is right ? the github sample or the blog post ?
one of the reasons i am asking is due to some seemingly odd routing i see when i used the blog post sample code .... i have it working but in swagger the api...
Thanks for the tutorial, my company stack is in OpenApi, and I would love to use OData as a “better rest”, but the lack of oficial client generators like in OpenApi is a no go.
Because in OpenApi you can generate a client in typescript, JavaScript, python, etc… On Odata no, and is limiting the evolution of this standart
Unfortunately this post is not working for me. It also seems to contain some errors, e.g. the instruction to call the endpoint refers to /odata/students but the controller code shows [Route("api/[controller]")], with api rather than odata. And the article doesn't say how to get the IEdmModel GetEdmModel() part of the Startup.cs code to build: I got this to build via adding the following using statements (but no idea if these are the correct...
Hi Patrick,
Thanks for pointing out the error in the post, I have fixed the controller code, although and as you may have noticed cloning the referenced github repo it doesn’t really have much impact as OData overrides that annotation.
Now, what I’m really wondering about is that whether the code I referenced in github works or not, please let us know, we’re happy to help.
Thanks for your great article.
Thank you, Adrien.
I have OData seeming to work but my results are not including the metadata and i am not sure why.
seems like it's just returning normal json data the data is valid just no metadata -- so i am not getting next link, row count etc...
trying to fix it but not sure where to make a change for it ....
UPDATE: it looks like there is something going on with asp.net core...
OData doesn’t support endpoint routing in ASP.NET Core yet, but the team is working on it as top priority.
Odata looks great! We have one question though.
Is it possible to pass the ODataQueryOptions to lower layers. We’re using micro services with MassTransit and want to pass the filter down to the appropriate micro service so it only returns the required data in the query rather than everything then the API filtering the data. We can’t return IQueryable from the micro service. Any way of dealing with this issue?
Hi Chris,
The answer is yes.
But in order for the ODataQueryOptions to take effect, you will need to get rid of the EnableQuery on your controller method otherwise it will apply the query twice.
Let me know if you have any questions.
I've played briefly with the information in the following link and just as the examples show you can get access to the parsed query parameters and then do whatever you need to. I'm in a bit of a holding pattern at the moment until the endpoint routing stuff gets sorted out. We just recently upgraded to .net core 3.1 and I'm not willing to start throwing our routing into legacy modes to...