Udostępnij za pomocą


Tworzenie wtyczki niestandardowej

Z tego artykułu dowiesz się, jak utworzyć niestandardową wtyczkę dla serwera proxy deweloperów. Tworząc wtyczki dla Dev Proxy, możesz rozszerzyć jego funkcjonalność i dodać funkcje niestandardowe, aby dostosować do swoich potrzeb.

Wymagania wstępne

Przed rozpoczęciem tworzenia wtyczki niestandardowej upewnij się, że masz następujące wymagania wstępne:

  • .NET v9 Core SDK
  • Najnowsza wersja biblioteki Dev Proxy Abstractions DLL, którą można znaleźć na stronie wydań Dev Proxy na GitHubie.

Tworzenie nowej wtyczki

Wykonaj następne kroki, aby utworzyć nowy projekt:

  1. Utwórz nowy projekt biblioteki klas przy użyciu dotnet new classlib polecenia .

    dotnet new classlib -n MyCustomPlugin
    
  2. Otwórz nowo utworzony projekt w programie Visual Studio Code.

    code MyCustomPlugin
    
  3. Dodaj bibliotekę DLL abstrakcji dev proxy (DevProxy.Abstractions.dll) do folderu projektu.

  4. Dodaj DevProxy.Abstractions.dll jako odwołanie do pliku projektu DevProxyCustomPlugin.csproj.

    <ItemGroup>
      <Reference Include="DevProxy.Abstractions">
        <HintPath>.\DevProxy.Abstractions.dll</HintPath>
        <Private>false</Private>
        <ExcludeAssets>runtime</ExcludeAssets>
      </Reference>
    </ItemGroup>
    
  5. Dodaj pakiety NuGet wymagane dla projektu.

    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.Binder
    dotnet add package Microsoft.Extensions.Logging.Abstractions
    dotnet add package Unobtanium.Web.Proxy
    
  6. Wyklucz zależne biblioteki DLL z danych wyjściowych kompilacji, poprzez dodanie tagu ExcludeAssets w pliku PackageReference na DevProxyCustomPlugin.csproj.

    <ExcludeAssets>runtime</ExcludeAssets>
    
  7. Utwórz nową klasę dziedziczącą z klasy 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)
        {
            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;
        }
    }
    
  8. Skompiluj projekt.

    dotnet build
    

Użyj swojej wtyczki niestandardowej

Aby użyć niestandardowej wtyczki, należy dodać ją do pliku konfiguracji serwera proxy deweloperów:

  1. Dodaj nową konfigurację wtyczki w pliku devproxyrc.json.

    {
      "plugins": [{
        "name": "CatchApiCallsPlugin",
        "enabled": true,
        "pluginPath": "./bin/Debug/net9.0/MyCustomPlugin.dll",
      }]
    }
    
  2. Uruchom serwer proxy deweloperów.

    devproxy
    

Przykładowa wtyczka sprawdza wszystkie pasujące adresy URL wymaganego Authorization nagłówka. Jeśli nagłówek nie jest obecny, zostanie wyświetlony komunikat ostrzegawczy.

Dodawanie konfiguracji niestandardowej do wtyczki (opcjonalnie)

Logikę wtyczki można rozszerzyć, dodając konfigurację niestandardową:

  1. Dziedzicz z klasy BasePlugin<TConfiguration>. Dev Proxy udostępnia w czasie działania składnię konfiguracji wtyczki poprzez właściwość 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(
        ILogger<CatchApiCallsPlugin> logger,
        ISet<UrlToWatch> urlsToWatch,
        IProxyConfiguration proxyConfiguration,
        IConfigurationSection pluginConfigurationSection) :
        BasePlugin<CatchApiCallsConfiguration>(
            logger,
            urlsToWatch,
            proxyConfiguration,
            pluginConfigurationSection)
    {
        public override string Name => nameof(CatchApiCallsPlugin);
    
        public override Task BeforeRequestAsync(ProxyRequestArgs e)
        {
            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. Skompiluj projekt.

    dotnet build
    
  3. devproxyrc.json Zaktualizuj plik, aby uwzględnić nową konfigurację.

    {
      "plugins": [{
        "name": "CatchApiCallsPlugin",
        "enabled": true,
        "pluginPath": "./bin/Debug/net9.0/MyCustomPlugin.dll",
        "configSection": "catchApiCalls"
      }],
      "catchApiCalls": {
        "requiredHeader": "Authorization" // Example configuration
      }
    }
    
  4. Uruchom serwer proxy deweloperów.

    devproxy