C# (ASP.NET Core)
在 ASP.NET Core 中,集成 ProxyTracer 最标准的方法是构建自定义管道中间件。这使得您能够在请求到达 MVC 控制器、Minimal API 或 Razor Pages 之前,在管道尽早阶段拦截恶意流量。
中间件实现
此中间件安全地从 HttpContext 提取客户端 IP(支持负载均衡器代理头配置),使用高效的 IHttpClientFactory 调用 ProxyTracer API,并在检测到威胁时以 403 Forbidden 立即终止请求管道。
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");
// 具有严格 500ms 超时的可复用客户端
_httpClient = new HttpClient { Timeout = TimeSpan.FromMilliseconds(500) };
}
public async Task InvokeAsync(HttpContext context)
{
// 1. 提取 IP(需要在 Program.cs 中配置 app.UseForwardedHeaders())
var ip = context.Connection.RemoteIpAddress?.ToString();
// 跳过本地开发环境 IP
if (!string.IsNullOrEmpty(ip) && ip != "127.0.0.1" && ip != "::1")
{
try
{
// 2. 异步查询 ProxyTracer API
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. 若检测到代理/VPN,则立即丢弃连接
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; // 提前终止请求处理管道
}
}
}
catch (Exception ex)
{
// 故障开放(Fail-open):记录错误并放行请求
_logger.LogWarning($"ProxyTracer validation failed: {ex.Message}");
}
}
// 4. 流量正常,继续放行至控制器
await _next(context);
}
// 精确映射到 {"proxy": true|false} 响应的轻量级结构体
private class ProxyTracerResult
{
[JsonPropertyName("proxy")]
public bool Proxy { get; set; }
}
}
}配置说明:
在 Program.cs 中注册该中间件。请确保将其置于路由中间件之前,以便在请求生命周期早期即阻断恶意连接。
var app = builder.Build();
// 1. 若位于 NGINX/Cloudflare 负载均衡器之后,确保提取真实客户端 IP
app.UseForwardedHeaders();
// 2. 尽早拦截恶意流量
app.UseMiddleware<ProxyTracer.Security.ProxyTracerMiddleware>();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();最后更新于