You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

.NET Core 2应用中如何设置代理绕过列表(bypasslist)

在ASP.NET Core API中配置代理绕过列表

在ASP.NET Core里,我们不再依赖传统ASP.NET的web.config<system.net>节点来配置代理绕过规则,而是通过代码直接配置HttpClient的处理程序,或者利用依赖注入体系来全局管理配置。下面是两种实用的实现方式:

方式1:为单个HttpClient实例配置绕过规则

如果你只需要给某一个特定的HttpClient设置代理绕过,可以手动创建WebProxy并添加匹配规则,再绑定到HttpClientHandler上:

// 创建WebProxy实例(若有固定代理服务器,可在此传入地址,比如new WebProxy("http://proxy.example.com:8080"))
var proxy = new WebProxy();

// 添加和你之前web.config一致的正则绕过规则
proxy.BypassArrayList.Add(new Regex(@"[a-z]+\.contoso\.com$"));
proxy.BypassArrayList.Add(new Regex(@"192\.168\.\d{1,3}\.\d{1,3}"));

// 开启本地地址自动绕过代理(不需要的话可设为false)
proxy.BypassProxyOnLocal = true;

// 配置HttpClientHandler并绑定代理
var handler = new HttpClientHandler
{
    Proxy = proxy,
    UseProxy = true
};

// 用配置好的handler创建HttpClient
var httpClient = new HttpClient(handler);

方式2:通过依赖注入全局注册(推荐)

在ASP.NET Core中,更推荐用IHttpClientBuilder来全局管理HttpClient配置,这样所有依赖注入的实例都会自动应用规则。在Program.cs中添加如下代码:

var builder = WebApplication.CreateBuilder(args);

// 注册带有代理绕过配置的命名HttpClient
builder.Services.AddHttpClient("ProxyAwareClient")
    .ConfigurePrimaryHttpMessageHandler(() =>
    {
        var proxy = new WebProxy();
        // 添加绕过规则
        proxy.BypassArrayList.Add(new Regex(@"[a-z]+\.contoso\.com$"));
        proxy.BypassArrayList.Add(new Regex(@"192\.168\.\d{1,3}\.\d{1,3}"));
        proxy.BypassProxyOnLocal = true;

        return new HttpClientHandler
        {
            Proxy = proxy,
            UseProxy = true
        };
    });

var app = builder.Build();

// 后续在控制器/服务中通过IHttpClientFactory获取实例
// 示例:
// private readonly HttpClient _httpClient;
// public MyController(IHttpClientFactory httpClientFactory)
// {
//     _httpClient = httpClientFactory.CreateClient("ProxyAwareClient");
// }

补充提示

  • 如果不需要指定固定代理服务器,仅需绕过特定地址,WebProxy的构造函数可以留空,它会自动使用系统默认代理设置,同时应用你的绕过规则。
  • BypassProxyOnLocal设为true时,所有本地地址(如localhost、局域网IP)都会自动绕过代理,可根据需求调整这个属性。

内容的提问来源于stack exchange,提问作者Ruben D. Lopez

火山引擎 最新活动