Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
The Open Data Protocol (OData) simplifies building and consuming RESTful APIs in Microsoft .NET development. It offers a standardized approach to querying and manipulating data through familiar CRUD (Create, Read, Update, Delete) operations. This article explores how Open Data Protocol streamlines API development in .NET, providing examples and highlighting its key benefits. To explore more about OData, you can check the OData C# GitHub Repository for the source code.
OData follows standard practices for building RESTful web APIs, using URLs and HTTP verbs like GET and POST to define operations. It represents data using an Entity Data Model (EDM) and JSON or AtomPub for message encoding. While OData simplifies API development compared to GraphQL, it may offer fewer advanced features.
The .NET libraries for OData enhance developer experience by facilitating efficient ways to manipulate data sets. It simplifies building and consuming RESTful APIs in .NET development. It offers a standardized approach to querying and manipulating data through familiar CRUD operations (Create, Read, Update, Delete).
Start by opening your new project in Visual Studio. Then, navigate to the Solution Explorer, right-click on your project, and select "Manage NuGet Packages". Search for Microsoft.AspNetCore.OData and install it. The current OData version is 8.2.5.
To install OData in the NuGet Package Manager Console, use the following command.
Install-Package Microsoft.AspNetCore.OData
Let's create a simple OData model class in an ASP.NET Core application. In the following code, the below class will expose a list of services that can be queried using the OData syntax.
public class Service
{
public int Id { get; set; }
public string FirstName { get; set; }
public decimal Price { get; set; }
}
public class Service
{
public int Id { get; set; }
public string FirstName { get; set; }
public decimal Price { get; set; }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
The Service
class represents a basic data structure in C# for managing a service. It includes three properties: Id: An integer identifier for the service. FirstName: A string representing the first name associated with the service. Price: A decimal value indicating the price of the service. This class can be used as a building block for creating more complex service-related functionality in .NET development. We may also use collection or navigation properties based on the scenario.
Here's how you can set up an OData controller in an ASP.NET Core application in Visual Studio to expose a list of services via a standardized OData endpoint. The following example demonstrates a basic implementation using a static list of services and enabling OData query functionalities in Web API:
using DemoOData.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;
namespace DemoOData.Controllers
{
[Route("odata/[controller]")]
public class ServiceController : ODataController
{
private static readonly List<Service> Products = new List<Service>
{
new Service { Id = 1, FirstName = "Laptop", Price = 6239.9M },
new Service { Id = 2, FirstName = "Smartphone", Price = 2585.9M }
};
[HttpGet]
[EnableQuery]
public IActionResult Get() => Ok(Products);
}
}
using DemoOData.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;
namespace DemoOData.Controllers
{
[Route("odata/[controller]")]
public class ServiceController : ODataController
{
private static readonly List<Service> Products = new List<Service>
{
new Service { Id = 1, FirstName = "Laptop", Price = 6239.9M },
new Service { Id = 2, FirstName = "Smartphone", Price = 2585.9M }
};
[HttpGet]
[EnableQuery]
public IActionResult Get() => Ok(Products);
}
}
Imports DemoOData.Models
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.AspNetCore.OData.Query
Imports Microsoft.AspNetCore.OData.Routing.Controllers
Namespace DemoOData.Controllers
<Route("odata/[controller]")>
Public Class ServiceController
Inherits ODataController
Private Shared ReadOnly Products As New List(Of Service) From {
New Service With {
.Id = 1,
.FirstName = "Laptop",
.Price = 6239.9D
},
New Service With {
.Id = 2,
.FirstName = "Smartphone",
.Price = 2585.9D
}
}
<HttpGet>
<EnableQuery>
Public Function [Get]() As IActionResult
Return Ok(Products)
End Function
End Class
End Namespace
The provided code defines an ODataController
named ServiceController
in an ASP.NET Core application, enabling querying and manipulating data using the OData protocol. It routes requests to odata/Service
and serves a static list of Service
objects, including a laptop and a smartphone. The Get
method, decorated with [EnableQuery]
, allows clients to perform OData queries (filtering, sorting, paging) on the Products list, returning the results as an IActionResult
for HTTP GET requests.
Register OData Services in the Program.cs
To integrate OData into a .NET 6 application, we need to install and configure the necessary OData packages. This involves defining the OData model, setting up the OData middleware, and configuring services to support OData features such as filtering, ordering, and expansion.
using DemoOData.Models;
using Microsoft.AspNetCore.OData;
using Microsoft.OData.Edm;
using Microsoft.OData.ModelBuilder;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Service>("Services");
return builder.GetEdmModel();
}
builder.Services.AddControllers()
.AddOData(options => options
.AddRouteComponents("odata", GetEdmModel())
.Select()
.Filter()
.OrderBy()
.SetMaxTop(20)
.Count()
.Expand()
);
using DemoOData.Models;
using Microsoft.AspNetCore.OData;
using Microsoft.OData.Edm;
using Microsoft.OData.ModelBuilder;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Service>("Services");
return builder.GetEdmModel();
}
builder.Services.AddControllers()
.AddOData(options => options
.AddRouteComponents("odata", GetEdmModel())
.Select()
.Filter()
.OrderBy()
.SetMaxTop(20)
.Count()
.Expand()
);
Imports DemoOData.Models
Imports Microsoft.AspNetCore.OData
Imports Microsoft.OData.Edm
Imports Microsoft.OData.ModelBuilder
Private builder = WebApplication.CreateBuilder(args)
' Add services to the container.
builder.Services.AddControllers()
' Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer()
builder.Services.AddSwaggerGen()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'static IEdmModel GetEdmModel()
'{
' ODataConventionModelBuilder builder = New ODataConventionModelBuilder();
' builder.EntitySet<Service>("Services");
' Return builder.GetEdmModel();
'}
builder.Services.AddControllers().AddOData(Function(options) options.AddRouteComponents("odata", GetEdmModel()).Select().Filter().OrderBy().SetMaxTop(20).Count().Expand())
This code configures OData support in a .NET 6 application. First, it imports necessary namespaces and creates a WebApplicationBuilder
instance. The GetEdmModel
method defines the OData model using the ODataConventionModelBuilder
, which specifies an entity set for Service
entities. The AddOData
method is then called to configure OData services, including enabling select, filter, order by, count, expand, and setting a maximum top value of 20 for query results. This setup ensures the application can handle OData queries effectively.
The AddOData()
method employs the GetEdmModel()
method, which retrieves the data model used for querying, forming the foundation of an OData service. This service utilizes an abstract data model known as Entity Data Model (EDM) to define the exposed data. The ODataConventionModelBuilder
class generates an EDM through default naming conventions, minimizing code requirements. Alternatively, developers can utilize the ODataModelBuilder
class for greater control over the EDM.
After running the service, you can query the Service using various OData query options, such as:
https://localhost:7131/odata/Service
IronPDF is a comprehensive C# library designed to simplify the conversion of files to PDF, splitting of PDF pages, and removal of pages from PDF within .NET applications. It offers a wide range of features, including the ability to generate PDFs from HTML, CSS, images, and JavaScript, enabling developers to effortlessly transform web content into high-quality PDF documents. With its intuitive API and powerful rendering engine, IronPDF empowers developers to streamline PDF generation processes, facilitating the integration of dynamic document generation capabilities into their applications with ease.
To install IronPDF in Visual Studio, navigate to NuGet Package Manager Console, and use the following command.
Install-Package IronPdf
To generate a PDF document from HTML content in a .NET application, we can use the ChromePdfRenderer
class from a library like DinkToPdf or similar. This example demonstrates how to create a PDF with details of an Employee record.
public record Employee (string FirstName, string LastName);
class Program
{
static void Main(string[] args)
{
var employee = new Employee("Iron", "Developer");
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf($"<h1>Person Record</h1><p>Name: {employee.FirstName} {employee.LastName}</p>");
pdf.SaveAs("PersonRecord.pdf");
}
}
public record Employee (string FirstName, string LastName);
class Program
{
static void Main(string[] args)
{
var employee = new Employee("Iron", "Developer");
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf($"<h1>Person Record</h1><p>Name: {employee.FirstName} {employee.LastName}</p>");
pdf.SaveAs("PersonRecord.pdf");
}
}
'INSTANT VB TODO TASK: C# 'records' are not converted by Instant VB:
'public record Employee(string FirstName, string LastName)
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim employee As New Employee("Iron", "Developer")
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf($"<h1>Person Record</h1><p>Name: {employee.FirstName} {employee.LastName}</p>")
pdf.SaveAs("PersonRecord.pdf")
End Sub
End Class
This example creates a simple Employee record and then uses IronPDF to generate a PDF document displaying the person's name. It showcases how seamlessly C# records can integrate with PDF generation in .NET applications.
OData simplifies the development and consumption of RESTful APIs in .NET by providing standardized querying and manipulation capabilities. We can also integrate it with Entity Framework, enhancing development efficiency by simplifying data access and management. OData streamlines API development, enabling seamless integration and interoperability across various platforms with its rich query functionalities and improved developer experience. Additionally, IronPDF offers comprehensive features and support for robust PDF manipulation within .NET applications.
OData, or Open Data Protocol, simplifies building and consuming RESTful APIs in .NET by providing a standardized approach to querying and manipulating data through CRUD operations.
OData offers standardization, rich query capabilities, improved developer experience, and interoperability. It reduces development complexity, allows efficient data retrieval, streamlines API development, and promotes broader application integration.
To set up OData in a .NET project, you can use Visual Studio to manage NuGet packages, search for Microsoft.AspNetCore.OData, and install it. Then, configure OData services in your project by defining the OData model and setting up the middleware.
ODataConventionModelBuilder is used to generate an Entity Data Model (EDM) using default naming conventions, minimizing code requirements for defining the OData model in .NET applications.
OData improves developer experience by providing pre-built components for routing, query handling, and data serialization, reducing code duplication, and development time.
IronPDF is a C# library that simplifies the conversion of files to PDF, splitting and removal of PDF pages, and generation of PDFs from HTML. It is used in .NET applications to streamline PDF generation processes.
Using IronPDF, you can generate a PDF by creating an HTML string and using the ChromePdfRenderer class to render it as a PDF document, which can be saved to a file.
The EnableQuery attribute in OData allows clients to perform OData queries such as filtering, sorting, and paging on the data exposed by an OData controller.
CRUD operations in OData refer to the standard operations of Create, Read, Update, and Delete, which are used to manipulate data in RESTful APIs.
OData promotes interoperability by allowing OData-compliant clients from various platforms to seamlessly interact with .NET-based OData services, enabling broader application integration.