hexarc pact
1.0.0
HEXARC PACT提供了一个工具链,用于曝光和消费基于.NET/打字稿项目的Web API。
通过PACT开发.NET Web API项目,以保留API元数据的单一真实来源,并在.NET生态系统(微服务,桌面和移动应用程序)或Web上通过Tyspecript消费。
| 包裹 | 平台 | 版本 | 下载 |
|---|---|---|---|
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