.NET 中 ODate 協議介紹
OData(Open Data Protocol)
是一個開放的 Web
協議,用于查詢和更新數據。在 .NET
生態系統中,OData
被廣泛支持和使用。
主要特性
1. 統一的數據訪問方式
- 提供標準化的查詢語法
- 支持
CRUD
操作 - 支持元數據描述
2. 查詢能力
標準查詢選項支持:
- 過濾數據(
$filter
) - 排序(
$orderby
) - 分頁(
$top, $skip
) - 投影,選擇字段(
$select
) - 擴展關聯數據(
$expand
)
.NET 9
增強功能:
- 性能改進:查詢執行和序列化性能優化
- 更好的路由集成:與
ASP.NET Core
路由系統更緊密集成 - 端點(
Endpoint
)路由支持:完全支持現代端點路由范式
3. 格式支持
JSON
格式(默認,推薦)XML
格式Atom
格式
版本支持
.NET
支持多個 OData
版本:
OData v4
(當前最新版本,推薦使用)OData v3
(較舊版本)
安全考慮
- 支持授權和認證
- 查詢復雜度限制
- 防止拒絕服務攻擊的機制
最佳實踐
- 正確設置查詢限制(
SetMaxTop
) - 使用
EnableQuery
特性控制查詢行為 - 實現適當的錯誤處理
- 考慮使用
DTO
避免暴露內部模型 - 啟用適當的緩存策略
優勢
- 標準化:遵循開放標準,便于與其他系統集成
- 靈活性:客戶端可以構建復雜的查詢
- 性能優化:支持服務端(
SSE
,ef core
服務端評估)分頁和投影字段選擇(CSE
,ef core
客戶端評估) - 工具支持:
Visual Studio
等工具提供良好支持
OData
遵循的國際標準:
- 核心標準
### OASIS 標準
- **OData Version 4.0**: 由 OASIS 組織發布的開放標準
- **OData JSON Format Version 4.0**: 定義 JSON 格式的數據交換規范
- **OData Common Schema Definition Language (CSDL) Version 4.0**: 實體數據模型定義語言### ISO/IEC 標準
- **ISO/IEC 20802-1:2016**: Information technology - Open Data Protocol (OData) - Part 1: Core
- **ISO/IEC 20802-2:2016**: Information technology - Open Data Protocol (OData) - Part 2: URL Conventions
- **ISO/IEC 20802-3:2016**: Information technology - Open Data Protocol (OData) - Part 3: Common Schema Definition Language (CSDL)
- 相關
Web
標準
### HTTP 標準
- **RFC 7231**: HTTP/1.1 Semantics and Content
- **RFC 7230-7237**: HTTP 協議系列標準
### URI 標準
- **RFC 3986**: Uniform Resource Identifier (URI): Generic Syntax
- 數據格式標準
- **ECMA-404**: The JSON Data Interchange Format
- **RFC 7493**: The I-JSON Message Format
- 其他相關標準
- **Atom Publishing Protocol (AtomPub)**: RFC 5023
- **OData Extension for Data Aggregation**: OASIS 標準擴展
這些標準確保了 OData
協議在全球范圍內的互操作性和標準化實施。
使用場景
- 構建
RESTful API
- 數據分析和報表系統
- 移動應用后端服務
- 微服務間的數據交互
·OData
協議為 .NET
開發者提供了一種強大而標準化的方式來構建數據服務 API
。
實現方式
.csproj
項目添加 nuget
相關包:
<Project Sdk="Microsoft.NET.Sdk.Web"><PropertyGroup><TargetFramework>net9.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup><ItemGroup><PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.7" /><PackageReference Include="Microsoft.AspNetCore.OData" Version="9.3.2" /><PackageReference Include="Microsoft.OData.ModelBuilder" Version="2.0.0" /><PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="9.0.7" /><PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.3" /></ItemGroup></Project>
說明:此處使用
EF Core
內存模式,模擬DB
數據庫,并添加OData
相關包。
目錄結構
完整目錄結構如下:
├─Controllers
├─Datatabase
│ ├─Entities
│ ├─Mappers
│ └─Repositories
├─Models
│ └─Dtos
├─Properties
└─Services
架構層次說明
這種實現保持了清晰的分層架構:
Controller 層:ProductsController
- 負責處理
HTTP
請求和響應 - 負責請求
DTO
的數據驗證 - 使用
OData
特性進行查詢支持 - 依賴服務層進行業務處理
Database 層:
- 數據庫相關的核心數據訪問層
- 包含實體、映射和倉儲模式的實現
- Database/Entities
- 存放數據實體類,包含數據結構定義,通常對應數據庫表結構
- 表示業務領域中的核心數據對象
- Database/Mappers
- 數據映射器,負責
Entity
(實體對象)與領域DTO
之間的轉換
- 數據映射器,負責
- Database/Repositories
- 倉儲模式實現,提供數據訪問的抽象接口
- 封裝數據訪問邏輯,提供
CRUD
操作
Service 層:ProductService
- 實現業務邏輯
- 協調多個倉儲操作
- 處理業務規則和驗證
- 依賴倉儲層進行數據訪問
Models 層:領域模型
- 包含數據結構定義
- 領域
DTO
模型 - 業務領域層中間轉換模型
這種架構模式的優勢:
- 關注點分離:每層職責明確
- 可測試性:各層可以獨立進行單元測試
- 可維護性:修改某一層不會(最小化)影響其他層
- 可擴展性:可以輕松添加新的業務邏輯或數據源
- 復用性:服務和倉儲可以在多個控制器中復用
詳細示例
- 創建數據庫表實體模型
namespace ODataDemo.Database.Entities;/// <summary>
/// 分類領域實體
/// </summary>
public class Category
{public required string Id { get; set; }public required string Name { get; set; }public required string Description { get; set; }public DateTime CreatedDate { get; set; }public bool IsActive { get; set; }// 導航屬性public ICollection<Product> Products { get; set; } = [];// 領域方法public void Activate() => IsActive = true;public void Deactivate(){IsActive = false;foreach (var product in Products){product.UpdateStock(-product.StockQuantity); // 清空庫存}}public bool CanDelete() => !Products.Any(p => p.IsInStock());
}/// <summary>
/// 產品領域實體
/// </summary>
public sealed class Product
{public required string Id { get; set; }public required string Name { get; set; }public required string Description { get; set; }public decimal Price { get; set; }public int StockQuantity { get; set; }public DateTime CreatedDate { get; set; }public DateTime UpdatedDate { get; set; }// 導航屬性public string CategoryId { get; set; } = string.Empty;public Category? Category { get; set; }// 領域方法public void UpdateStock(int quantity){if (quantity < 0 && Math.Abs(quantity) > StockQuantity){throw new InvalidOperationException("庫存不足");}StockQuantity += quantity;UpdatedDate = DateTime.UtcNow;}public bool IsInStock() => StockQuantity > 0;public void ApplyDiscount(decimal discountPercentage){if (discountPercentage < 0 || discountPercentage > 100){throw new ArgumentException("折扣百分比必須在0-100之間");}Price = Price * (1 - discountPercentage / 100);UpdatedDate = DateTime.UtcNow;}
}
- 創建
DTO
對象
using System.Text.Json.Serialization;namespace ODataDemo.Models.Dtos;//#######################################
// 分類數據傳輸對象,用于 OData API
//#######################################public class CategoryRequstDto
{[JsonPropertyName("name")]public required string Name { get; set; }[JsonPropertyName("description")]public required string Description { get; set; }[JsonPropertyName("is_active")]public bool IsActive { get; set; }
}public sealed class CategoryResponeDto : CategoryRequstDto
{[JsonPropertyName("id")]public required string Id { get; set; }[JsonPropertyName("created_date")]public DateTime CreatedDate { get; set; }[JsonPropertyName("product_count")]public int ProductCount { get; set; }
}//############################################
// 產品數據傳輸對象,用于 OData API
//############################################public class ProductRequstDto
{[JsonPropertyName("name")]public required string Name { get; set; }[JsonPropertyName("description")]public required string Description { get; set; }[JsonPropertyName("price")]public decimal Price { get; set; }[JsonPropertyName("stock_quantity")]public int StockQuantity { get; set; }[JsonPropertyName("category_id")]public string CategoryId { get; set; } = string.Empty;[JsonPropertyName("category_name")]public string CategoryName { get; set; } = string.Empty;[JsonPropertyName("is_in_stock")]public bool IsInStock { get; set; }
}public sealed class ProductResponeDto : ProductRequstDto
{[JsonPropertyName("id")]public required string Id { get; set; }[JsonPropertyName("created_date")]public DateTime CreatedDate { get; set; }[JsonPropertyName("updated_date")]public DateTime UpdatedDate { get; set; }
}
Entity
映射DTO
處理
using ODataDemo.Database.Entities;
using ODataDemo.Models.Dtos;namespace ODataDemo.Database.Mappers;public static class CategoryMapper
{public static Category From(this CategoryRequstDto dto){return new Category(){Id = Guid.CreateVersion7().ToString(),Name = dto.Name,Description = dto.Description,CreatedDate = DateTime.UtcNow,IsActive = dto.IsActive,};}public static CategoryResponeDto ToModel(this Category entity){return new CategoryResponeDto{Id = entity.Id,Name = entity.Name,Description = entity.Description,IsActive = entity.IsActive,CreatedDate = entity.CreatedDate,ProductCount = entity.Products.Count,};}
}public static class ProductMapper
{public static Product From(this ProductRequstDto dto){return new Product(){Id = Guid.CreateVersion7().ToString(),Name = dto.Name,Description = dto.Description,Price = dto.Price,StockQuantity = dto.StockQuantity,CreatedDate = DateTime.UtcNow,UpdatedDate = DateTime.UtcNow,CategoryId = dto.CategoryId};}public static ProductResponeDto ToModel(this Product entity){return new ProductResponeDto{Id = entity.Id,Name = entity.Name,Description = entity.Description,Price = entity.Price,StockQuantity = entity.StockQuantity,CreatedDate = entity.CreatedDate,UpdatedDate = entity.UpdatedDate,CategoryId = entity.CategoryId,CategoryName = entity.Category?.Name ?? string.Empty,IsInStock = entity.IsInStock()};}
}
- 定義倉儲規范
說明:在倉儲層,只出現數據庫表對應的實體對象
Entity
。
using ODataDemo.Database.Entities;namespace ODataDemo.Database.Repositories;public interface IDataRepository
{#region ProductIQueryable<Product> GetProducts();Task<Product?> GetProductByIdAsync(string id);Task<Product> AddProductAsync(Product product);Task<Product> UpdateProductAsync(Product product);Task DeleteProductAsync(string id);Task<bool> ExistsProductAsync(string id);#endregion#region CategoryIQueryable<Category> GetCategorys();Task<Category?> GetCategoryByIdAsync(string id);Task<Category> AddCategoryAsync(Category category);Task<Category> UpdateCategoryAsync(Category category);Task DeleteCategoryAsync(string id);Task<bool> ExistsCategoryAsync(string id);#endregion
}
- 定義服務規范
說明:服務層只出現
DTO
對象,在實現內部處理Entity
和DTO
的轉換。
using ODataDemo.Models.Dtos;namespace ODataDemo.Services;public interface ICategoryService
{IQueryable<CategoryResponeDto> GetAllCategories();Task<CategoryResponeDto?> GetCategoryByIdAsync(string id);Task<CategoryResponeDto> CreateCategoryAsync(CategoryRequstDto category);Task<CategoryResponeDto> UpdateCategoryAsync(string id, CategoryRequstDto category);Task DeleteCategoryAsync(string id);Task ActivateCategoryAsync(string id);Task DeactivateCategoryAsync(string id);
}public interface IProductService
{IQueryable<ProductResponeDto> GetProducts();Task<ProductResponeDto?> GetProductByIdAsync(string id);Task<ProductResponeDto> CreateProductAsync(ProductRequstDto dto);Task<ProductResponeDto> UpdateProductAsync(string id, ProductRequstDto dto);Task DeleteProductAsync(string id);Task ApplyDiscountAsync(string productId, decimal discountPercentage);Task UpdateStockAsync(string productId, int quantity);
}
- 配置
EDM
模型
說明:
EDM
配置是關鍵,更多信息請查看相關資料,篇幅有限不再詳述。
相關資料:
- 使用 OData 簡化 EDM
using Microsoft.OData.Edm;
using Microsoft.OData.ModelBuilder;
using ODataDemo.Models.Dtos;namespace ODataDemo.Database;public static class EdmModelConfig
{// 配置 EDM 模型public static IEdmModel GetEdmModel(){var builder = new ODataConventionModelBuilder();// 只注冊 DTO 類型var productDto = builder.EntityType<ProductResponeDto>();productDto.HasKey(p => p.Id);productDto.Property(p => p.Name);productDto.Property(p => p.Description);productDto.Property(p => p.Price);productDto.Property(p => p.StockQuantity);productDto.Property(p => p.CategoryId);productDto.Property(p => p.CreatedDate);productDto.Property(p => p.IsInStock);productDto.Property(p => p.CreatedDate);productDto.Property(p => p.UpdatedDate);var categoryDto = builder.EntityType<CategoryResponeDto>();categoryDto.HasKey(c => c.Id);categoryDto.Property(c => c.Name);categoryDto.Property(c => c.Description);categoryDto.Property(p => p.IsActive);categoryDto.Property(p => p.CreatedDate);categoryDto.Property(p => p.ProductCount);// 使用 DTO 創建實體集builder.EntitySet<ProductResponeDto>("Products");builder.EntitySet<CategoryResponeDto>("Categories");return builder.GetEdmModel();}
}
- 配置
AppDbContext
說明:在此處添加一些初始化的種子數據。
using Microsoft.EntityFrameworkCore;
using ODataDemo.Database.Entities;namespace ODataDemo.Database;public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{public DbSet<Product> Products { get; set; }public DbSet<Category> Categories { get; set; }protected override void OnModelCreating(ModelBuilder modelBuilder){string id1 = Guid.CreateVersion7().ToString();string id2 = Guid.CreateVersion7().ToString();string id3 = Guid.CreateVersion7().ToString();// Seed datamodelBuilder.Entity<Category>().HasData(new Category { Id = id1, Name = "Electronics", Description = "Electronic devices" },new Category { Id = id2, Name = "Books", Description = "Books and literature" },new Category { Id = id3.ToString(), Name = "Clothing", Description = "Apparel and accessories" });modelBuilder.Entity<Product>().HasData(new Product { Id = Guid.CreateVersion7().ToString(), Name = "Laptop", Price = 1200.00m, StockQuantity = 50, CategoryId = id1, Description = "High-performance laptop" },new Product { Id = Guid.CreateVersion7().ToString(), Name = "Mouse", Price = 25.00m, StockQuantity = 100, CategoryId = id1, Description = "Wireless mouse" },new Product { Id = Guid.CreateVersion7().ToString(), Name = "Keyboard", Price = 75.00m, StockQuantity = 75, CategoryId = id1, Description = "Mechanical keyboard" },new Product { Id = Guid.CreateVersion7().ToString(), Name = "C# Programming Guide", Price = 45.00m, StockQuantity = 30, CategoryId = id2, Description = "Comprehensive C# guide" },new Product { Id = Guid.CreateVersion7().ToString(), Name = "T-Shirt", Price = 20.00m, StockQuantity = 200, CategoryId = id3, Description = "Cotton t-shirt" });base.OnModelCreating(modelBuilder);}
}
說明:添加兩個
Swagger
和OData
相關的處理
- 支持
OData
查詢參數顯示
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;namespace ODataDemo.Filters;public class SwaggerDefaultValues : IOperationFilter
{public void Apply(OpenApiOperation operation, OperationFilterContext context){var apiDescription = context.ApiDescription;// 檢查是否標記為過時var isDeprecated = context.MethodInfo.GetCustomAttribute<ObsoleteAttribute>() != null;if (isDeprecated){operation.Deprecated = true;}// 添加默認響應if (operation.Parameters == null){operation.Parameters = [];}// 為每個參數添加默認值和描述foreach (var parameter in operation.Parameters){var description = apiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name);parameter.Description ??= description.ModelMetadata?.Description;if (parameter.Schema.Default == null &&description.DefaultValue != null &&description.DefaultValue is not DBNull &&description.ModelMetadata?.ModelType != null){var json = System.Text.Json.JsonSerializer.Serialize(description.DefaultValue);parameter.Schema.Default = OpenApiAnyFactory.CreateFromJson(json);}parameter.Required |= description.IsRequired;}// 為 OData 操作添加通用參數說明if (context.ApiDescription.HttpMethod == "GET"){AddODataQueryParameters(operation);}}private void AddODataQueryParameters(OpenApiOperation operation){var odataParameters = new List<(string name, string description)>{("$filter", "Filters the results based on a Boolean condition"),("$orderby", "Sorts the results"),("$top", "Returns only the first n results"),("$skip", "Skips the first n results"),("$select", "Selects which properties to include in the response"),("$expand", "Expands related entities inline"),("$count", "Includes a count of the total number of items")};foreach (var (name, description) in odataParameters){if (!operation.Parameters.Any(p => p.Name == name)){operation.Parameters.Add(new OpenApiParameter{Name = name,In = ParameterLocation.Query,Description = description,Schema = new OpenApiSchema{Type = "string"},Required = false});}}}
}
- 處理
OData
特定類型的序列化問題
using Microsoft.AspNetCore.OData.Deltas;
using Microsoft.AspNetCore.OData.Results;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;namespace ODataDemo.Filters;public class ODataSchemaFilter : ISchemaFilter
{public void Apply(OpenApiSchema schema, SchemaFilterContext context){// 處理 OData 特定類型的序列化問題if (context.Type.IsGenericType &&(context.Type.GetGenericTypeDefinition() == typeof(SingleResult<>) ||context.Type.GetGenericTypeDefinition() == typeof(Delta<>))){// 對于 SingleResult<T> 和 Delta<T>,使用泛型參數類型var genericType = context.Type.GetGenericArguments()[0];// 可以根據需要自定義 schema}}
}
- 控制器實現
注意:控制器繼承
ODataController
,沒有[ApiController]
和[Route]
特性
//[Route(“api/[controller]”)]
//[ApiController]
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Deltas;
using Microsoft.AspNetCore.OData.Formatter;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Results;
using Microsoft.AspNetCore.OData.Routing.Controllers;
using ODataDemo.Models.Dtos;
using ODataDemo.Services;namespace ODataDemo.Controllers;public class ProductsController(IProductService productService) : ODataController
{// GET /odata/Products[EnableQuery]public IActionResult Get(){return Ok(productService.GetProducts());}// GET /odata/Products(1) - 使用標準命名和路由[EnableQuery]public SingleResult<ProductResponeDto> Get([FromODataUri] string key){var result = productService.GetProducts().Where(p => p.Id == key);return SingleResult.Create(result);}// POST /odata/Productspublic async Task<IActionResult> Post([FromBody] ProductRequstDto dto){if (!ModelState.IsValid){return BadRequest(ModelState);}var result = await productService.CreateProductAsync(dto);return Created(result);}// PUT /odata/Products(1)public async Task<IActionResult> Put([FromRoute] string key, [FromBody] ProductRequstDto dto){if (!ModelState.IsValid){return BadRequest(ModelState);}var result = await productService.UpdateProductAsync(key, dto);return Updated(result);}// PATCH /odata/Products(1)public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] Delta<ProductRequstDto> delta){var product = await productService.GetProductByIdAsync(key);if (product == null){return NotFound();}delta.Patch(product);var result = await productService.UpdateProductAsync(key, product);return Updated(result);}// DELETE /odata/Products(1)public async Task<IActionResult> Delete([FromRoute] string key){await productService.DeleteProductAsync(key);return NoContent();}
}
Program.cs
代碼示例:
using Microsoft.AspNetCore.OData;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using ODataDemo.Data.Repositories;
using ODataDemo.Database;
using ODataDemo.Database.Repositories;
using ODataDemo.Filters;
using ODataDemo.Services;var builder = WebApplication.CreateBuilder(args);// Add services to the container.// 添加 API 探索器(必需)
builder.Services.AddEndpointsApiExplorer();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
//builder.Services.AddOpenApi();// 添加 Swagger 生成器(必需)
builder.Services.AddSwaggerGen(options =>
{options.SwaggerDoc("v1", new OpenApiInfo{Version = "v1",Title = "OData API",Description = "An ASP.NET Core OData API"});// 支持 OData 查詢參數顯示options.OperationFilter<SwaggerDefaultValues>();// 處理 OData 類型序列化問題options.SchemaFilter<ODataSchemaFilter>();options.CustomSchemaIds(type => type.ToString());
});// 添加控制器和 OData 服務
builder.Services.AddControllers().AddOData(options =>{// 啟用分頁相關查詢選項options.Select().Filter().OrderBy().Expand().Count().SetMaxTop(100); // 設置每頁最大記錄數// 使用 Convention-based 路由options.AddRouteComponents("odata", EdmModelConfig.GetEdmModel());// 關鍵配置:啟用大小寫不敏感options.RouteOptions.EnablePropertyNameCaseInsensitive = true;options.RouteOptions.EnableControllerNameCaseInsensitive = true;options.RouteOptions.EnableActionNameCaseInsensitive = true;});// 添加數據庫上下文
builder.Services.AddDbContext<AppDbContext>(options =>options.UseInMemoryDatabase("ODataDemo"));// 注冊db倉儲服務
builder.Services.AddScoped<IDataRepository, DataRepository>();
// 注冊業務服務
builder.Services.AddScoped<ICategoryService, CategoryService>();
builder.Services.AddScoped<IProductService, ProductService>();var app = builder.Build();// 初始化數據庫
using (var scope = app.Services.CreateScope())
{var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();context.Database.EnsureCreated();
}// Configure the HTTP request pipeline.
// 啟用路由
app.UseRouting();if (app.Environment.IsDevelopment())
{// 添加錯誤處理中間件app.Use(async (context, next) =>{try{await next();}catch (Exception ex){if (context.Request.Path.StartsWithSegments("/swagger")){Console.WriteLine("Swagger Error:");}Console.WriteLine($"Stack Trace: {ex.StackTrace}");await context.Response.WriteAsync(ex.Message);}});// 使用 swaggerapp.UseSwagger();app.UseSwaggerUI(options =>{options.SwaggerEndpoint("/swagger/v1/swagger.json", "OData API v1");options.RoutePrefix = "swagger";});
}app.UseAuthorization();
app.MapControllers();await app.RunAsync();
啟動項目
啟動項目,顯示如下頁面,其中包含兩個接口,分別是產品和分類,另外還有一個源數據信息接口。
使用 Apipost
工具,訪問源數據接口:
http://localhost:5108/odata/
其他接口類似,此處就不再詳述。
最后附上完整示例截圖,感興趣的小伙伴歡迎點贊關注喲。
總結
ASP.NET Core WebAPI
和 OData
的集成提供了一種標準化、高性能的方式來構建數據驅動的 REST API
,大大簡化了復雜查詢接口的開發工作。
可以增強擴展統一的數據響應格式,比如 ApiResponse
,統一的異常數據格式等。