OData C# (如何為開發人員運作)
開放資料協定(OData)簡化了在Microsoft .NET開發中構建和使用RESTful APIs。 它提供了一種標準化的方法來通過熟悉的CRUD(建立、讀取、更新、刪除)操作查詢和操作資料。 本文探討了開放資料協定如何簡化.NET中的API開發,提供範例並突顯其關鍵優勢。 要了解更多有關OData的資訊,您可以參考OData C# GitHub Repository以獲取原始碼。

OData遵循標準的實踐方法來構建RESTful web APIs,使用URL和HTTP動詞如GET和POST來定義操作。 它使用實體資料模型(EDM)和JSON或AtomPub來進行消息編碼。 儘管OData相比GraphQL簡化了API開發,但它可能提供較少的高級功能。

使用OData在.NET中的好處
- 標準化:OData強制一種一致的方法來定義實體資料模型、處理請求和格式化回應。 這減少了開發的複雜性並簡化了使用者端應用程式的整合。
- 豐富的查詢功能:OData支援統一的資料查詢方式以執行CRUD操作、過濾($filter)、排序(升序/降序)($orderby)和分頁($top, $skip)功能,允許使用者端有效地檢索特定資料集。
- 改善的開發者體驗:OData的.NET程式庫簡化了API開發。 開發者可以利用預先建置的元件來進行路由、查詢處理和資料序列化,從而減少程式碼複製和開發時間。
- 互操作性:來自各個平臺的OData合規使用者端可以無縫地與您的基於.NET的OData服務進行互動,促進更廣泛的應用程式整合。
在** .NET框架中**開始使用OData
OData的.NET程式庫通過促進高效的資料集操作提高了開發者體驗。 它簡化了在.NET開發中的RESTful APIs的構建和使用。 它通過熟悉的CRUD操作(建立、讀取、更新、刪除)提供了一種標準化的資料查詢和操作方法。
在.NET專案中設置OData
首先,在Visual Studio中開啟您的新專案。 然後,導航到方案總管,右鍵點擊您的專案,並選擇"管理NuGet封裝"。 搜尋Microsoft.AspNetCore.OData並安裝。 當前的OData版本是8.2.5。
要在NuGet封裝管理器主控台中安裝OData,請使用以下命令。

範例:在ASP.NET Core中建立OData服務
讓我們在一個ASP.NET Core應用程式中建立一個簡單的OData模型類別。 在以下程式碼中,下方類別將透過OData語法公開可查詢的服務清單。
public class Service
{
public int Id { get; set; }
public string FirstName { get; set; }
public decimal Price { get; set; }
}Public Class Service
Public Property Id As Integer
Public Property FirstName As String
Public Property Price As Decimal
End ClassPublic Class Service
Public Property Id As Integer
Public Property FirstName As String
Public Property Price As Decimal
End Class程式碼說明
Service類別在C#中表示一個基本資料結構以管理服務。它包括三個屬性:Id:服務的整數識別符。FirstName:代表與服務相關的名字的字串。Price:指示服務價格的十進位值。這個類別可以作為在.NET開發中建立更複雜的服務相關功能的基石。 我們也可以根據場景使用集合或導航屬性。
以下是在Visual Studio中設定一個ASP.NET Core應用程式的OData控制器以通過標準化的OData端點公開服務清單的方法。 以下範例演示了一個基本的實現,使用靜態服務清單並啟用Web API中的OData查詢功能:
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 NamespaceImports 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程式碼說明
提供的程式碼定義了一個在ASP.NET Core應用程式中命名為ServiceController,啟用使用OData協定的資料查詢和操作。 它將請求路由到Service物件清單,包括一台筆記本電腦和一部智慧型手機。 [EnableQuery],允許使用者端對產品清單進行OData查詢(過濾、排序、分頁),並將結果作為HTTP GET請求的IActionResult返回。
在Program.cs中註冊OData服務
要將OData整合到.NET 6應用程式中,我們需要安裝並配置必要的OData封裝。 這涉及定義OData模型、設置OData中介軟體,以及配置服務以支持OData功能,如過濾、排序和擴展。
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())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())程式碼說明
這個程式碼配置了.NET 6應用程式中OData的支援。 首先,它導入必要的命名空間並建立一個WebApplicationBuilder實例。 Service實體的實體集。 然後調用AddOData方法來配置OData服務,包括啟用選擇、過濾、排序、計數、擴展,並為查詢結果設置最大頂值為20。 這個設置確保應用程式能夠有效地處理OData查詢。
GetEdmModel()方法來獲取用於查詢的資料模型,形成OData服務的基礎。此服務利用一個稱為實體資料模型(EDM)的抽象資料模型來定義所公開的資料。 ODataConventionModelBuilder類別通過預設命名約定來生成EDM,減少了程式碼需求。 或者,開發者可以利用ODataModelBuilder類別獲得對EDM的更高控制權。
程式碼截圖

運行服務
運行服務後,您可以使用各種OData查詢選項來查詢服務,例如:
https://localhost:7131/odata/Service
程式輸出

簡介 IronPDF
IronPDF是一個全面的C#程式庫,旨在簡化.NET應用程式中將檔案轉換為PDF,拆分PDF頁面和從PDF中刪除頁面。 它提供了廣泛的功能,包括從HTML、CSS、圖片和JavaScript生成PDF,讓開發者輕鬆地將網頁內容轉換為高質量的PDF文件。 憑藉其直觀的API和強大的渲染引擎,IronPDF讓開發者能夠簡化PDF的生成過程,輕鬆地將動態文件生成功能整合到其應用程式中。

將IronPDF新增至專案
要在Visual Studio中安裝IronPDF,請導航到NuGet包管理器主控台,並使用以下命令。
生成PDF
要在.NET應用程式中從HTML內容生成PDF文件,可以使用像DinkToPdf或類似的程式庫中的ChromePdfRenderer類別。 此範例演示如何建立一個包含員工記錄詳細資訊的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");
}
}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'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該範例建立一個簡單的員工記錄,然後使用IronPDF生成顯示人名的PDF文件。 它展示了C#記錄如何與.NET應用程式中的PDF生成無縫整合。

結論
OData通過提供標準化的查詢和操作功能來簡化.NET中的RESTful APIs的開發和使用。 我們也可以將其與Entity Framework結合使用,通過簡化資料存取和管理來提高開發效率。 OData簡化了API的開發,通過其豐富的查詢功能和改進的開發者體驗實現跨多個平臺的無縫整合和互操作性。 此外,IronPDF提供了全面的功能和支援,用於在.NET應用程式中進行強大的PDF操作。
Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。