Lezen in het Engels

Delen via


Een aangepaste invoegtoepassing maken

In dit artikel leert u hoe u een aangepaste invoegtoepassing maakt voor de Dev Proxy. Door invoegtoepassingen voor Dev Proxy te maken, kunt u de functionaliteit uitbreiden en aangepaste functies toevoegen aan uw behoeften.

Vereisten

Voordat u begint met het maken van een aangepaste invoegtoepassing, moet u ervoor zorgen dat u aan de volgende vereisten voldoet:

Een nieuwe invoegtoepassing maken

Volg de volgende stappen om een nieuw project te maken:

  1. Maak een nieuw klassebibliotheekproject met behulp van de dotnet new classlib opdracht.

    Console
    dotnet new classlib -n MyCustomPlugin
    
  2. Open het zojuist gemaakte project in Visual Studio Code.

    Console
    code MyCustomPlugin
    
  3. Voeg het DLL-bestand Dev Proxy Abstractions (dev-proxy-abstractions.dll) toe aan de projectmap.

  4. Voeg het dev-proxy-abstractions.dll bestand toe als verwijzing naar het projectbestand DevProxyCustomPlugin.csproj .

    XML
    <ItemGroup>
      <Reference Include="dev-proxy-abstractions">
        <HintPath>.\dev-proxy-abstractions.dll</HintPath>
        <Private>false</Private>
        <ExcludeAssets>runtime</ExcludeAssets>
      </Reference>
    </ItemGroup>
    
  5. Voeg de NuGet-pakketten toe die vereist zijn voor uw project.

    Console
    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. Sluit de afhankelijkheids-DLL's uit van de build-uitvoer door een ExcludeAssets tag per PackageReference in het DevProxyCustomPlugin.csproj bestand toe te voegen.

    XML
    <ExcludeAssets>runtime</ExcludeAssets>
    
  7. Maak een nieuwe klasse waarmee de BaseProxyPlugin interface wordt geïmplementeerd.

    C#
    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. Bouw uw project.

    Console
    dotnet build
    

Uw aangepaste invoegtoepassing gebruiken

Als u uw aangepaste invoegtoepassing wilt gebruiken, moet u deze toevoegen aan het configuratiebestand van de Dev Proxy:

  1. Voeg de nieuwe configuratie van de invoegtoepassing toe aan het devproxyrc.json bestand.

    JSON
    {
      "plugins": [{
        "name": "CatchApiCalls",
        "enabled": true,
        "pluginPath": "./bin/Debug/net8.0/MyCustomPlugin.dll",
      }]
    }
    
  2. Voer de dev-proxy uit.

    Console
    devproxy
    

De voorbeeldinvoegtoepassing controleert alle overeenkomende URL's voor de vereiste autorisatieheader. Als de koptekst niet aanwezig is, wordt er een waarschuwingsbericht weergegeven.

Aangepaste configuratie toevoegen aan uw invoegtoepassing (optioneel)

U kunt de logica van uw invoegtoepassing uitbreiden door aangepaste configuratie toe te voegen:

  1. Voeg een nieuw _configuration object toe en bind het in de Register methode.

    C#
    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. Bouw uw project.

    Console
    dotnet build
    
  3. Werk uw devproxyrc.json bestand bij om de nieuwe configuratie op te nemen.

    JSON
    {
      "plugins": [{
        "name": "CatchApiCalls",
        "enabled": true,
        "pluginPath": "./bin/Debug/net8.0/MyCustomPlugin.dll",
        "configSection": "catchApiCalls"
      }],
      "catchApiCalls": {
        "requiredHeader": "Authorization" // Example configuration
      }
    }
    
  4. Voer de dev-proxy uit.

    Console
    devproxy