Udostępnij za pośrednictwem


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:

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 (dev-proxy-abstractions.dll) do folderu projektu.

  4. Dodaj dev-proxy-abstractions.dll jako odwołanie do pliku projektu DevProxyCustomPlugin.csproj.

    <ItemGroup>
      <Reference Include="dev-proxy-abstractions">
        <HintPath>.\dev-proxy-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 DevProxyCustomPlugin.csproj na PackageReference.

    <ExcludeAssets>runtime</ExcludeAssets>
    
  7. Utwórz nową klasę, która implementuje BaseProxyPlugin interfejs.

    using Microsoft.DevProxy.Abstractions;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    
    namespace MyCustomPlugin;
    
    public class CatchApiCalls(IPluginEvents pluginEvents, IProxyContext context, ILogger logger, ISet<UrlToWatch> UrlsToWatch, IConfigurationSection? configSection = null) : BaseProxyPlugin(pluginEvents, context, logger, UrlsToWatch, configSection)
    {
      public override string Name => nameof(CatchApiCalls);
    
      public override async Task RegisterAsync()
      {
        await base.RegisterAsync();
    
        PluginEvents.BeforeRequest += BeforeRequestAsync;
      }
    
      private Task BeforeRequestAsync(object sender, ProxyRequestArgs e)
      {
        if (UrlsToWatch is null ||
          !e.HasRequestUrlMatch(UrlsToWatch))
        {
          // No match for the URL, so we don't need to do anything
          Logger.LogRequest("URL not matched", MessageType.Skipped, new LoggingContext(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;
        }
    
        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": "CatchApiCalls",
        "enabled": true,
        "pluginPath": "./bin/Debug/net8.0/MyCustomPlugin.dll",
      }]
    }
    
  2. Uruchom serwer proxy deweloperów.

    devproxy
    

Przykładowa wtyczka sprawdza wszystkie pasujące adresy URL dla wymaganego nagłówka autoryzacji. 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. Dodaj nowy _configuration obiekt i powiąż go w metodzie Register .

    using Microsoft.DevProxy.Abstractions;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    
    namespace MyCustomPlugin;
    
    public class CatchApiCallsConfiguration
    {
      public string? RequiredHeader { get; set; }
    }
    
    public class CatchApiCalls(IPluginEvents pluginEvents, IProxyContext context, ILogger logger, ISet<UrlToWatch> UrlsToWatch, IConfigurationSection? configSection = null) : BaseProxyPlugin(pluginEvents, context, logger, UrlsToWatch, configSection)
    {
      public override string Name => nameof(CatchApiCalls);
    
      // Define you custom configuration
      private readonly CatchApiCallsConfiguration _configuration = new();
    
      public override async Task RegisterAsync()
      {
        await base.RegisterAsync();
    
        // Bind your plugin configuration
        configSection?.Bind(_configuration);
    
        // Register your event handlers
        PluginEvents.BeforeRequest += BeforeRequestAsync;
      }
    
      private Task BeforeRequestAsync(object sender, ProxyRequestArgs e)
      {
        if (UrlsToWatch is null ||
          !e.HasRequestUrlMatch(UrlsToWatch))
        {
          // No match for the URL, so we don't need to do anything
          Logger.LogRequest("URL not matched", MessageType.Skipped, new LoggingContext(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;
        }
    
        return Task.CompletedTask;
      }
    }
    
  2. Skompiluj projekt.

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

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

    devproxy