建立自定義外掛程式

一目了然
目標: 建立一個自訂的開發代理插件
時間: 30分鐘
插件: 自訂外掛
Prerequisites:Set Dev Proxy.NET 10 SDK

在本文中,您將瞭解如何為 Dev Proxy 建立自定義插件。 藉由建立開發 Proxy 的外掛程式,您可以擴充其功能,並新增自定義功能以符合您的需求。

HTTP 插件與標準外掛

Dev Proxy 支援兩種外掛,視你想攔截的流量而定:

  • HTTP 外掛 會攔截你的應用程式與 API 之間的 HTTP(S) 請求與回應。 它們繼承自 BasePlugin,並覆寫像 BeforeRequestAsyncBeforeResponseAsync 這樣的方法。 當你想模擬 API 錯誤、新增模擬回應、驗證請求標頭,或以其他方式檢查和修改 HTTP 流量時,請使用 HTTP 外掛。

  • Stdio 外掛 會攔截父程序與子程序之間透過標準輸入/輸出(stdin、stdout、stderr)傳送的訊息。 它們實作了 IStdioPlugin 介面(BasePlugin 也有實作該介面),並覆寫如 BeforeStdinAsyncAfterStdoutAsyncAfterStderrAsync 等方法。 在使用透過 stdio 通訊的工具工作時,請使用 stdio 外掛,例如模型情境協定(MCP)伺服器。

單一外掛類別可透過覆寫 HTTP 與 stdio 兩組方法來處理兩者流量。

必要條件

開始建立自定義外掛程式之前,請確定您具備下列必要條件:

建立新的外掛程式

請遵循後續步驟來建立新的專案:

  1. 使用 dotnet new classlib 命令建立新的類別庫專案。

    dotnet new classlib -n MyCustomPlugin
    
  2. 在 Visual Studio Code 中開啟新建立的專案。

    code MyCustomPlugin
    
  3. 將 Dev Proxy Abstractions NuGet 套件加入你的專案。

    dotnet add package DevProxy.Abstractions
    
  4. MyCustomPlugin.csproj 檔案中,為每個 PackageReference 新增一個 ExcludeAssets 標籤,從建置輸出中排除相依的動態連結程式庫(DLL)。

    <ExcludeAssets>runtime</ExcludeAssets>
    
  5. 建立繼承自 BaseProxy 類別的新類別。

    using DevProxy.Abstractions.Plugins;
    using DevProxy.Abstractions.Proxy;
    using Microsoft.Extensions.Logging;
    
    namespace MyCustomPlugin;
    
    public sealed class CatchApiCallsPlugin(
        ILogger<CatchApiCallsPlugin> logger,
        ISet<UrlToWatch> urlsToWatch) : BasePlugin(logger, urlsToWatch)
    {
        public override string Name => nameof(CatchApiCallsPlugin);
    
        public override Task BeforeRequestAsync(ProxyRequestArgs e, CancellationToken cancellationToken)
        {
            Logger.LogTrace("{Method} called", nameof(BeforeRequestAsync));
    
            ArgumentNullException.ThrowIfNull(e);
    
            if (!e.HasRequestUrlMatch(UrlsToWatch))
            {
                Logger.LogRequest("URL not matched", MessageType.Skipped, new(e.Session));
                return Task.CompletedTask;
            }
    
            var headers = e.Session.HttpClient.Request.Headers;
            var header = headers.Where(h => h.Name == "Authorization").FirstOrDefault();
            if (header is null)
            {
                Logger.LogRequest($"Does not contain the Authorization header", MessageType.Warning, new LoggingContext(e.Session));
                return Task.CompletedTask;
            }
    
            Logger.LogTrace("Left {Name}", nameof(BeforeRequestAsync));
            return Task.CompletedTask;
        }
    }
    
  6. 建立您的專案。

    dotnet build
    

使用您的自定義外掛程式

若要使用您的自定義外掛程式,您必須將它新增至 Dev Proxy 組態檔:

  1. devproxyrc.json檔案中新增外掛程式的設定。

    檔案: devproxyrc.json

    {
      "plugins": [{
        "name": "CatchApiCallsPlugin",
        "enabled": true,
        "pluginPath": "./bin/Debug/net10.0/MyCustomPlugin.dll",
      }]
    }
    
  2. 執行開發代理伺服器。

    devproxy
    

此範例外掛程式會檢查所有相符 URL 是否有符合要求的 Authorization 標頭。 如果標頭不存在,它會顯示警告訊息。

將自訂元件新增至您的外掛程式 (選擇性)

您可以藉由新增自訂元件來擴充外掛程式的邏輯:

  1. 繼承自 BasePlugin<TConfiguration> 類別。 在運行時,開發代理會透過 Configuration 屬性公開剖析的外掛程式配置。

    using DevProxy.Abstractions.Plugins;
    using DevProxy.Abstractions.Proxy;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    
    namespace MyCustomPlugin;
    
    public sealed class CatchApiCallsConfiguration
    {
        public string? RequiredHeader { get; set; }
    }
    
    public sealed class CatchApiCallsPlugin(
        HttpClient httpClient,
        ILogger<CatchApiCallsPlugin> logger,
        ISet<UrlToWatch> urlsToWatch,
        IProxyConfiguration proxyConfiguration,
        IConfigurationSection pluginConfigurationSection) :
        BasePlugin<CatchApiCallsConfiguration>(
            httpClient,
            logger,
            urlsToWatch,
            proxyConfiguration,
            pluginConfigurationSection)
    {
        public override string Name => nameof(CatchApiCallsPlugin);
    
        public override Task BeforeRequestAsync(ProxyRequestArgs e, CancellationToken cancellationToken)
        {
            Logger.LogTrace("{Method} called", nameof(BeforeRequestAsync));
    
            ArgumentNullException.ThrowIfNull(e);
    
            if (!e.HasRequestUrlMatch(UrlsToWatch))
            {
                Logger.LogRequest("URL not matched", MessageType.Skipped, new(e.Session));
                return Task.CompletedTask;
            }
    
            // Start using your custom configuration
            var requiredHeader = Configuration.RequiredHeader ?? string.Empty;
            if (string.IsNullOrEmpty(requiredHeader))
            {
                // Required header is not set, so we don't need to do anything
                Logger.LogRequest("Required header not set", MessageType.Skipped, new LoggingContext(e.Session));
                return Task.CompletedTask;
            }
    
            var headers = e.Session.HttpClient.Request.Headers;
            var header = headers.Where(h => h.Name == requiredHeader).FirstOrDefault();
            if (header is null)
            {
                Logger.LogRequest($"Does not contain the {requiredHeader} header", MessageType.Warning, new LoggingContext(e.Session));
                return Task.CompletedTask;
            }
    
            Logger.LogTrace("Left {Name}", nameof(BeforeRequestAsync));
            return Task.CompletedTask;
        }
    }
    
  2. 建立您的專案。

    dotnet build
    
  3. 更新您的 devproxyrc.json 檔案以包含新的組態。

    檔案: devproxyrc.json

    {
      "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v3.0.0/rc.schema.json",
      "plugins": [{
        "name": "CatchApiCallsPlugin",
        "enabled": true,
        "pluginPath": "./bin/Debug/net10.0/MyCustomPlugin.dll",
        "configSection": "catchApiCalls"
      }],
      "catchApiCalls": {
        "requiredHeader": "Authorization"
      }
    }
    
  4. 執行開發代理伺服器。

    devproxy
    

另請參閱