OData (Open Data Protocol) is an ISO/IEC approved, OASIS standard that defines a set of best practices for building and consuming RESTful APIs. This post is about implementing OData (Open Data Protocol) in ASP.NET 6.0. OData RESTful APIs are easy to consume. The OData metadata, a machine-readable description of the data model of the APIs, enables the creation of powerful generic client proxies and tools. Unfortunetly OData is not available as part of Minimal APIs. So first let’s create a Web API application using the
dotnet new webapi command. Once you created the API project add reference of
Next you can modify the
builder.Services.AddControllers() method in
Program.cs like this.
Now you’re configured ASP.NET Core app to work with OData. And finally you need to add the
EnableQuery attribute to the controller
Now you’re ready to consume the endpoint with OData protocols.
You can open your browser and open the following URL -
https://localhost:5001/WeatherForecast?$select=Summary and you will be able to see like this.
The select query you help you to select a particular field from the JSON response. You can filter the results using a query like this -
https://localhost:5001/WeatherForecast?$filter=Summary eq 'Hot' - which will return JSON results where Summary field is
Hot. You can order by fields using Order by parameter -
https://localhost:5001/WeatherForecast?$orderby=Date - this will return results ordered by the Date. Since the
MaxTop method is added, you can get paged results as well - Like the LINQ paging -
Unlike ASP.NET Core 5.0, you don’t need to write any formatters or anything for OData to work with Open API (Swagger).
Here few helpful links which talks about OData in ASP.NET Core.
Happy Programming :)