如何解决Httpclienthandler Webproxy值未更改
有人可以帮我吗。将boolean属性设置为true会有一点问题。
在这里,我为代理创建了一个类,以便可以从Winform设置并调用它到我的httpclient类。
class MyProxy
{
public static bool UseProxy { get; set; }
public static string ProxyHost { get; set; } = string.Empty;
public static string ProxyPort { get; set; } = string.Empty;
}
如果我不想使用代理,这是可选的
private static HttpClientHandler handler = new HttpClientHandler
{
UseDefaultCredentials = false,PreAuthenticate = true,Proxy = new WebProxy($"http://{MyProxy.ProxyHost}:{MyProxy.ProxyPort}",false),UseProxy = MyProxy.UseProxy,// i want to change this if I want to use the proxy or not
};
所以在我的主要表单中,我有一个复选框(无论是否使用代理)
private void TEST()
{
bool isCheck = cbUseProxy.Checked;
//so here I'll check first if isCheck is true
MyProxy.UseProxy = isCheck;
//here I call my httpclient class
}
问题是,如果我首先设置或首先选中复选框(即useProxy),则Webproxy将获取该值。并且我取消选中(不使用代理)webproxy仍然获得第一个值(这是真的)。
我想将UseProxy(来自WebProxy)的值从true更改为false,将false更改为true。
更新后的最终解决方案:(感谢@Milney的建议。我认为这是解决方案)
private static HttpClientHandler handler = new HttpClientHandler
{
PreAuthenticate = true,UseDefaultCredentials = false,Proxy = null,UseProxy = false,};
private static HttpClientHandler handlerWithProxy = new HttpClientHandler
{
PreAuthenticate = true,UseProxy = true,};
private static readonly HttpClient client = new HttpClient(handler);
private static readonly HttpClient clientWithProxy = new HttpClient(handlerWithProxy);
然后在我的ResponseMessage上
private static async Task<JsonDocument> ResponseMessage(HttpRequestMessage request,CancellationToken token)
{
HttpCompletionOption option = HttpCompletionOption.ResponseHeadersRead;
bool useProxy = MyProxy.UseProxy;
using (var response = useProxy ? await clientWithProxy.SendAsync(request,option,token).ConfigureAwait(false)
: await client.SendAsync(request,token).ConfigureAwait(false))
{
token.ThrowIfCancellationRequested();
using (var contentStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
var json = await ParseJsonFromStream(contentStream);
if (!response.IsSuccessStatusCode)
{
if (json != null)
{
throw new InvalidDataException($"Error occured: {ParseError(uri,json)}");
}
}
return json;
}
}
}
解决方法
在创建HttpClientHandler时,MyProxy.UseProxy具有其默认值。 如果稍后更改它,它将不会自动“流动”到客户端处理程序属性。您需要重新创建HttpClientHandler,或者在实际获得要使用的值后至少重置其属性...
private void TEST()
{
bool isCheck = cbUseProxy.Checked;
// You have to set the property on the handler
// It won't automatically refresh from your other class
handler.UseProxy = isCheck;
//here I call my httpclient class
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。