Skip to Content
DocumentationBackend-LaufzeitenASP.NET Core (C#)

C# (ASP.NET Core)

Für Microsoft-Unternehmensumgebungen stellt die direkte Integration von ProxyTracer in die ASP.NET Core HTTP-Anforderungspipeline sicher, dass bösartiger Datenverkehr abgewiesen wird, bevor er Routing, Model Binding oder Datenbankabfragen auslöst.

Die Middleware

Diese Implementierung verwendet System.Text.Json für eine ultraschnelle Deserialisierung, erzwingt ein strenges Timeout über HttpClient und bricht die Pipeline mit einer 403 Forbidden-Antwort ab, falls markiert.

using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace ProxyTracer.Security { public class ProxyTracerMiddleware { private readonly RequestDelegate _next; private readonly HttpClient _httpClient; private readonly ILogger<ProxyTracerMiddleware> _logger; private readonly string _apiKey; public ProxyTracerMiddleware(RequestDelegate next, IConfiguration config, ILogger<ProxyTracerMiddleware> logger) { _next = next; _logger = logger; _apiKey = config["PROXYTRACER_API_KEY"] ?? throw new ArgumentNullException("PROXYTRACER_API_KEY is missing"); // Reusable client with strict 500ms timeout _httpClient = new HttpClient { Timeout = TimeSpan.FromMilliseconds(500) }; } public async Task InvokeAsync(HttpContext context) { // 1. Extract the IP (Requires app.UseForwardedHeaders() configured in Program.cs) var ip = context.Connection.RemoteIpAddress?.ToString(); // Skip local development IPs if (!string.IsNullOrEmpty(ip) && ip != "127.0.0.1" && ip != "::1") { try { // 2. Query ProxyTracer API asynchronously using var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.proxytracer.com/v1/check/{ip}"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey); using var response = await _httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { using var jsonStream = await response.Content.ReadAsStreamAsync(); var ptResponse = await JsonSerializer.DeserializeAsync<ProxyTracerResult>(jsonStream); // 3. Drop the connection if a proxy/VPN is detected if (ptResponse != null && ptResponse.Proxy) { context.Response.StatusCode = StatusCodes.Status403Forbidden; context.Response.ContentType = "application/json"; await context.Response.WriteAsync("{\"error\": \"Access Denied: VPN or Proxy detected.\"}"); return; // Short-circuit the request pipeline } } } catch (Exception ex) { // Fail open: Log the error and allow the request through _logger.LogWarning($"ProxyTracer validation failed: {ex.Message}"); } } // 4. Traffic is clean, proceed to controllers await _next(context); } // Lightweight struct mapping exactly to the {"proxy": true|false} response private class ProxyTracerResult { [JsonPropertyName("proxy")] public bool Proxy { get; set; } } } }

Konfiguration

Um den Schutz zu aktivieren, registrieren Sie die Middleware in Ihrer Program.cs-Datei. Stellen Sie sicher, dass sie nach UseForwardedHeaders, aber vor UseRouting und UseAuthentication platziert wird.

var app = builder.Build(); // 1. Ensure real IPs are extracted if behind an NGINX/Cloudflare load balancer app.UseForwardedHeaders(); // 2. Drop malicious traffic early app.UseMiddleware<ProxyTracer.Security.ProxyTracerMiddleware>(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();
Last updated on