Dela via


Skapa ett anpassat plugin-program

I den här artikeln får du lära dig hur du skapar ett anpassat plugin-program för Dev Proxy. Genom att skapa plugin-program för Dev Proxy kan du utöka dess funktioner och lägga till anpassade funktioner så att de passar dina behov.

Förutsättningar

Innan du börjar skapa ett anpassat plugin-program kontrollerar du att du har följande förutsättningar:

Skapa ett nytt plugin-program

Följ nästa steg för att skapa ett nytt projekt:

  1. Skapa ett nytt klassbiblioteksprojekt med kommandot dotnet new classlib .

    dotnet new classlib -n MyCustomPlugin
    
  2. Öppna det nyligen skapade projektet i Visual Studio Code.

    code MyCustomPlugin
    
  3. Lägg till Dev Proxy Abstractions DLL (DevProxy.Abstractions.dll) i projektmappen.

  4. Lägg till DevProxy.Abstractions.dll som en referens i din projektDevProxyCustomPlugin.csprojfil.

    <ItemGroup>
      <Reference Include="DevProxy.Abstractions">
        <HintPath>.\DevProxy.Abstractions.dll</HintPath>
        <Private>false</Private>
        <ExcludeAssets>runtime</ExcludeAssets>
      </Reference>
    </ItemGroup>
    
  5. Lägg till De NuGet-paket som krävs för projektet.

    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. Undanta beroende-DLL:er från byggutdata genom att lägga till en ExcludeAssets tagg per PackageReference i DevProxyCustomPlugin.csproj filen.

    <ExcludeAssets>runtime</ExcludeAssets>
    
  7. Skapa en ny klass som ärver från BaseProxy klassen.

    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. Skapa ditt projekt.

    dotnet build
    

Använda ditt anpassade plugin-program

Om du vill använda ditt anpassade plugin-program måste du lägga till det i konfigurationsfilen för Dev Proxy:

  1. Lägg till den nya plugin-konfigurationen devproxyrc.json i filen.

    {
      "plugins": [{
        "name": "CatchApiCallsPlugin",
        "enabled": true,
        "pluginPath": "./bin/Debug/net9.0/MyCustomPlugin.dll",
      }]
    }
    
  2. Kör Dev Proxy.

    devproxy
    

Exempelpluginet kontrollerar alla matchande URL:er för den nödvändiga Authorization headern. Om rubriken inte finns visas ett varningsmeddelande.

Lägga till anpassad konfiguration i plugin-programmet (valfritt)

Du kan utöka logiken för plugin-programmet genom att lägga till anpassad konfiguration:

  1. Ärv från BasePlugin<TConfiguration> klassen. Dev Proxy exponerar vid körtid pluginens konfiguration med hjälp av Configuration-egenskapen.

    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. Skapa ditt projekt.

    dotnet build
    
  3. devproxyrc.json Uppdatera filen så att den innehåller den nya konfigurationen.

    {
      "plugins": [{
        "name": "CatchApiCallsPlugin",
        "enabled": true,
        "pluginPath": "./bin/Debug/net9.0/MyCustomPlugin.dll",
        "configSection": "catchApiCalls"
      }],
      "catchApiCalls": {
        "requiredHeader": "Authorization" // Example configuration
      }
    }
    
  4. Kör Dev Proxy.

    devproxy