Net Core设置代理
有时候我们需要使用代理去调用某些外部接口,浏览器的代理IIS 读取不到,所以只能项目里面指定代理
- 通过在Startup.cs 文件配置HttpClient
services.AddHttpClient("configured-inner-handler")
.ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler()
{
// AllowAutoRedirect = false,
// UseDefaultCredentials = true,
Proxy = new WebProxy(Configuration["Proxy"]),
UseProxy = true
};
});
2.调用刚刚配置的HttpClient
private readonly HttpClient client;
public BaseCoreService(IConfiguration configuration, IHttpClientFactory IHttpClientFactory,ILogger<BaseCoreService> logger) {
client = IHttpClientFactory.CreateClient("configured-inner-handler");
}
var request = new HttpRequestMessage(HttpMethod.Get, "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=" + $@"{appid}&secret={secret}&js_code={code.Trim()}");
HttpResponseMessage response = await client.SendAsync(request);