【问题标题】:Edit Web.Config - "System.Net" Section Programmatically?以编程方式编辑 Web.Config -“System.Net”部分?
【发布时间】:2015-07-07 16:16:46
【问题描述】:
我想更改 web.config 中的“system.net”部分。我想根据运行时的变量添加或删除 defaultProxy 标记。
<defaultProxy enabled="true" useDefaultCredentials="false">
<module type = "XXX.Utils.YYProxy, XXX" />
</defaultProxy>
我知道,有编辑web.config的相关帖子,但它们都与ConnectionStringsSection或AppSettingsSection相关。 System.Configuration 包中有关于它们的特定类,但我没有找到任何与“system.net”相关的类。
你知道有什么快速的处理方法吗?提前致谢
【问题讨论】:
标签:
c#
asp.net
web-config
edit
system.net
【解决方案1】:
我找到了一种方法来做到这一点。我使用以下代码启用或禁用 defaultProxy 标记:
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
NetSectionGroup netSection = (NetSectionGroup)config.GetSectionGroup("system.net");
if (string.IsNullOrEmpty(model.ProxyUrl))
netSection.DefaultProxy.Enabled = false;
else
netSection.DefaultProxy.Enabled = true;
关键是将 SectionGroup 转换为 NetSectionGroup 类。
【解决方案2】:
我建议不要从 web.config 中删除 defaultProxy 元素,而是在您的代码中,根据分配给您引用的变量的值覆盖所使用的代理。
例如:
WebRequest request = WebRequest.Create("http://stackoverflow.com/");
if(variable == "some expected value to override default proxy") {
//by setting the Proxy property of the Request object to a new WebProxy class, you override the default
request.Proxy = new WebProxy("http://someproxyserver.com:80", true);
}
当然,我需要查看更多您的代码才能给出更完整的答案。
希望这会有所帮助!