共用方式為


開始使用 YARP

YARP 是設計成提供核心的代理功能的程式庫,您可以藉由新增或取代模組來自定義。 YARP 目前以 NuGet 套件和程式代碼範例的形式提供。 我們計劃在未來提供專案範本和預先建置的可執行檔(.exe)。

YARP 是在 .NET 基礎結構之上實作,可在 Windows、Linux 或 MacOS 上使用。 使用 SDK 和您慣用的編輯器開發應用程式, Microsoft Visual StudioVisual 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應用程式,為專案範本選擇 [空白]。

新增套件參考

新增 Yarp.ReverseProxy2.3.0 版或以上版本的套件參考。

dotnet add package Yarp.ReverseProxy

Note

如需將套件新增至 .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();

Configuration

YARP 的組態定義於 appsettings.json 檔案中。 如需詳細資訊,請參閱 YARP 組態檔

您也可以以程式設計方式提供組態。 如需詳細資訊,請參閱 YARP 擴充性設定提供者

若要深入瞭解可用的組態選項,請參閱 RouteConfigClusterConfig

{
 "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 中,按兩下 [ 執行 ] 按鈕來啟動應用程式。