hexarc pact
1.0.0
HEXARC PACT提供了一個工具鏈,用於曝光和消費基於.NET/打字稿項目的Web API。
使用PACT開發.NET Web API項目,以保留API元數據的單個真實來源,並在.NET生態系統(微服務,桌面和移動應用程序)或Web上通過Tyxpycript消費。
| 包裹 | 平台 | 版本 | 下載 |
|---|---|---|---|
Hexarch.Pact.Protocol | .NET 7.0+ | ||
Hexarch.Pact.AspNetCore | .NET 7.0+ | ||
Hexarch.Pact.Client | .NET 7.0+ | ||
Hexarch.Pact.Tool | .NET 7.0+ | ||
@hexarc/pact-tool | 打字稿 |
PACT類型系統基於具有一些定制開發體驗的.NET CLR類型。
PACT類型系統內部是什麼:
Guid和DateTime )PACT API模式設計為具有RPC樣語義。這樣一來,暴露的API必須遵循以下規則:
ApiController和Route屬性標記。[Route("Entities")] )。HttpGet或HttpPost )標記。動詞屬性可能包含端點路徑。目前不支持其他人。HttpGet方法可以具有必須通過FromQuery屬性綁定的查詢參數。HttpPost方法必須只有一個參數,即請求主體。Route屬性中指定API方法路徑。如果未在HTTP動詞屬性中指定方法路徑,則將從一號Route中取出或將提高例外。PACT為API註釋提供了一些有用的屬性:
PactIgnoreAttribute可以應用於API控制器或用於從API模式中排除的方法。PactScopeAttribute可以應用於API控制器,以分離為API模式中的特定範圍。 可以在https://hexarc-demo-api.herokuapp.com/上找到演示API服務器。
PACT API模式在https://hexarc-demo-api.herokuapp.com/pact/schema上暴露。
要生成API客戶端,請使用以下指令。
找出如何使用PACT暴露和消費典型的Web API。
Hexarc.Pact.AspNetCore軟件包: dotnet add package Hexarc.Pact.AspNetCoreStartup.ConfigureServices中添加PACT模式生成。 Configureservices方法: public void ConfigureServices ( IServiceCollection services )
{
services . AddControllers ( ) ;
// Register the Pact schema generation.
services . AddPactGeneration ( ) ;
}Startup.Configure中啟用PACT中間件。配置方法: public void Configure ( IApplicationBuilder app )
{
// Enable the Pact middleware to expose the generated API schema.
app . UsePact ( ) ;
app . UseRouting ( ) ;
app . UseEndpoints ( endpoints => endpoints . MapControllers ( ) ) ;
} [ ApiController , Route ( "Misc" ) ]
public sealed class MiscController : ControllerBase
{
[ HttpGet ( nameof ( Ping ) ) ]
public String Ping ( [ FromQuery ] String message ) => $ "Hello, { message } " ;
}YOUR_API_HOST/pact/schema地址,以確保生成PACT API架構。Hexarc.Pact.Client軟件包: dotnet add package Hexarc.Pact.ClientHexarc.Pact.Tool工具: dotnet tool install Hexarc.Pact.Tool在安裝Hexarc.Pact.Tool工具之前,您可能需要設置.NET工具宣言:
dotnet new tool-manifestpact.json配置,並具有所需的API客戶端生成設置: {
"schemaUri" : " YOUR_API_HOST/pact/schema " ,
"clientClassName" : " DemoClient " ,
"clientClassNamespace" : " DemoNamespace " ,
"outputDirectory" : " Generated "
}在哪裡
schemaUri鏈接到PACT API模式clientClassName生成的API客戶端類的名稱clientClassNamespace名稱空間在生成的API客戶端類中outputDirectory生成源的輸出目錄dotnet pact此命令必須使用pact.json config在同一文件夾中執行。
var client = new DemoClient ( new HttpClient { BaseAddress = new Uri ( "YOUR_API_HOST" ) } ) ;
var pong = await client . Misc . Ping ( "World" ) ;
Console . WriteLine ( pong ) ; // Prints "Hello, World" to the output. 由用於開源項目的噴氣橋工具構建。
麻省理工學院©Max Koverdyaev