简体   繁体   中英

Edit Web.Config - “System.Net” Section Programmatically?

I want to change the "system.net" section in web.config. I want to add or remove defaultProxy tag according to a variable in runtime.

<defaultProxy enabled="true" useDefaultCredentials="false">
  <module type = "XXX.Utils.YYProxy, XXX" />
</defaultProxy>

I know, there are related posts editing web.config, but they all related with ConnectionStringsSection or AppSettingsSection . There are specific classes about them in System.Configuration package, but I did not find any class related with "system.net".

Do you know any quick way to handle this? Thanks in advance

I found a way to do this. I enable or disable the defaultProxy tag with following code:

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;

The key point was casting the SectionGroup to NetSectionGroup class.

Instead of removing the defaultProxy element from web.config, I recommend that, in your code, you override the proxy that is used based on the value assigned to the variable to which you refer.

For example:

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);
}

Of course, I'd need to see more of your code to give a more complete answer.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM