Aracılığıyla paylaş


Özel eklenti oluşturma

Bir bakışta
Hedef: Özel Geliştirme Ara Sunucusu eklentisi oluşturma
Süre: 30 dakika
Eklentiler: Özel eklenti
Önkoşullar:Geliştirme Proxy'si, .NET 9 SDK'sını ayarlama

Bu makalede, Geliştirme Proxy'si için özel eklenti oluşturmayı öğreneceksiniz. Dev Proxy için eklentiler oluşturarak işlevselliğini genişletebilir ve gereksinimlerinize uygun özel özellikler ekleyebilirsiniz.

Önkoşullar

Özel eklenti oluşturmaya başlamadan önce aşağıdaki önkoşullara sahip olduğunuzdan emin olun:

Yeni eklenti oluşturma

Yeni bir proje oluşturmak için sonraki adımları izleyin:

  1. komutunu kullanarak dotnet new classlib yeni bir sınıf kitaplığı projesi oluşturun.

    dotnet new classlib -n MyCustomPlugin
    
  2. Yeni oluşturulan projeyi Visual Studio Code'da açın.

    code MyCustomPlugin
    
  3. Dev Proxy Abstractions DLL'sini (DevProxy.Abstractions.dll) proje klasörüne ekleyin.

  4. DevProxy.Abstractions.dll öğesini proje DevProxyCustomPlugin.csproj dosyanıza başvuru olarak ekleyin.

    <ItemGroup>
      <Reference Include="DevProxy.Abstractions">
        <HintPath>.\DevProxy.Abstractions.dll</HintPath>
        <Private>false</Private>
        <ExcludeAssets>runtime</ExcludeAssets>
      </Reference>
    </ItemGroup>
    
  5. Projeniz için gereken NuGet paketlerini ekleyin.

    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. ExcludeAssets dosyasında her PackageReference için bir DevProxyCustomPlugin.csproj etiketi ekleyerek bağımlılık DLL'lerini derleme çıktısının dışında tutun.

    <ExcludeAssets>runtime</ExcludeAssets>
    
  7. sınıfından BaseProxy devralan yeni bir sınıf oluşturun.

    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;
        }
    }
    
  8. Projenizi derleyin.

    dotnet build
    

Özel eklentinizi kullanma

Özel eklentinizi kullanmak için Geliştirme Ara Sunucusu yapılandırma dosyasına eklemeniz gerekir:

  1. Yeni eklenti yapılandırmasını dosyaya devproxyrc.json ekleyin.

    Dosya: devproxyrc.json

    {
      "plugins": [{
        "name": "CatchApiCallsPlugin",
        "enabled": true,
        "pluginPath": "./bin/Debug/net9.0/MyCustomPlugin.dll",
      }]
    }
    
  2. Geliştirme Proxy'sini çalıştırın.

    devproxy
    

Örnek eklenti, gerekli Authorization üst bilgi için tüm eşleşen URL'leri denetler. Başlık yoksa bir uyarı mesajı gösterilir.

Eklentinize özel yapılandırma ekleme (isteğe bağlı)

Özel yapılandırma ekleyerek eklentinizin mantığını genişletebilirsiniz:

  1. BasePlugin<TConfiguration> sınıfından devralın. Dev Proxy, çalışma zamanında ayrıştırılmış eklenti yapılandırmasını Configuration özelliği aracılığıyla kullanıma sunar.

    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. Projenizi derleyin.

    dotnet build
    
  3. Dosyanızı devproxyrc.json yeni yapılandırmayı içerecek şekilde güncelleştirin.

    Dosya: devproxyrc.json

    {
      "plugins": [{
        "name": "CatchApiCallsPlugin",
        "enabled": true,
        "pluginPath": "./bin/Debug/net9.0/MyCustomPlugin.dll",
        "configSection": "catchApiCalls"
      }],
      "catchApiCalls": {
        "requiredHeader": "Authorization" // Example configuration
      }
    }
    
  4. Geliştirme Proxy'sini çalıştırın.

    devproxy
    

Ayrıca bakınız