控制WebRequest代理
时间:2011-04-26 来源:Ryan R
private void ProxySetting(WebRequest request)
{
WebProxy proxy = WebProxy.GetDefaultProxy();//获取IE缺省设置 //如果缺省设置为空,则有可能是根本不需要代理服务器,如果此时配置文件中也未配置则认为不需Proxy
if (proxy.Address == null)//按配置文件创建Proxy 地置
{
string address = "http://"+ConfigurationUtil.ProxyAddress + ":" + ConfigurationUtil.ProxyPort;
proxy.Address = new Uri(address);
}
if (proxy.Address != null)//如果地址为空,则不需要代理服务器
{
proxy.Credentials = new NetworkCredential(ConfigurationUtil.UserName, ConfigurationUtil.Password);//从配置封装参数中创建
request.Proxy = proxy;//赋予 request.Proxy
}
}
if (Convert.ToBoolean(ConfigurationUtil.IsProxy))
{
ProxySetting(request);
}
internal class ConfigurationUtil
{
public static string IsProxy
{
get
{
if (string.IsNullOrEmpty(_IsProxy))
{
_IsProxy = ConfigurationManager.AppSettings["IsProxy"];
}
return _IsProxy;
}
}
public static string ProxyAddress
{
get
{
if (string.IsNullOrEmpty(_proxyAddress))
{
_proxyAddress = ConfigurationManager.AppSettings["ProxyAddress"];
}
return _proxyAddress;
}
}
public static string ProxyPort
{
get
{
if (string.IsNullOrEmpty(_proxyPort))
{
_proxyPort = ConfigurationManager.AppSettings["ProxyPort"];
}
return _proxyPort;
}
}
public static string UserName
{
get
{
if (string.IsNullOrEmpty(_userName))
{
_userName = ConfigurationManager.AppSettings["UserName"];
}
return _userName;
}
}
public static string Password
{
get
{
if (string.IsNullOrEmpty(_password))
{
_password = ConfigurationManager.AppSettings["Password"];
}
return _password;
}
}
private static string _proxyAddress;
private static string _proxyPort;
private static string _userName;
private static string _password;
private static string _IsProxy;
}
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="IsProxy" value="False"/>
<add key="ProxyAddress" value="192.168.1.222"/>
<add key="ProxyPort" value="8080"/>
<add key="UserName" value="xxxx"/>
<add key="Password" value="123"/>
</appSettings>