YARP 设计为提供核心代理功能的库,可以通过添加或替换模块进行自定义。 YARP 目前以 NuGet 包和代码示例的形式提供。 我们计划在将来提供项目模板和预生成可执行文件(.exe
)。
YARP 是在 .NET Core 基础结构的基础上实现的,可在 Windows、Linux 或 MacOS 上使用。 可以使用 SDK 和你喜欢的编辑器完成开发,Microsoft Visual Studio 或 Visual Studio Code。
YARP 2.3.0 支持 .NET 8 或更高版本。
可以从 https://dotnet.microsoft.com/download/dotnet/下载 .NET SDK。
创建新项目
可以在 基本 YARP 示例找到使用以下步骤生成的项目的完整版本。
首先,使用命令行创建空的 ASP.NET Core 应用程序:
dotnet new web -n MyProxy
或者,在 Visual Studio 2022 中创建新的 ASP.NET Core Web 应用程序,为项目模板选择“空”。
添加包引用
请添加 2.3.0 或更高版本的包引用 Yarp.ReverseProxy
。
dotnet add package Yarp.ReverseProxy
注释
有关将包添加到 .NET 应用的指南,请参阅包使用工作流(NuGet 文档)中“安装和管理包”下的文章。 在 NuGet.org 中确认正确的包版本。
添加 YARP 中间件
更新 Program
文件以使用 YARP 中间件:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
var app = builder.Build();
app.MapReverseProxy();
app.Run();
配置
YARP 的配置在 appsettings.json
文件中定义。 有关详细信息,请参阅 YARP 配置文件。
还可以以编程方式提供配置。 有关详细信息,请参阅 YARP 扩展性配置提供程序。
通过查看 RouteConfig 和 ClusterConfig,您可以了解有关可用配置选项的更多信息。
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ReverseProxy": {
"Routes": {
"route1" : {
"ClusterId": "cluster1",
"Match": {
"Path": "{**catch-all}"
}
}
},
"Clusters": {
"cluster1": {
"Destinations": {
"destination1": {
"Address": "https://example.com/"
}
}
}
}
}
}
运行项目
使用 .NET CLI 时,请在示例的目录中使用 dotnet run
或 dotnet run --project <path to .csproj file>
。
在 Visual Studio 中,单击“ 运行 ”按钮启动应用。