Reputation: 903
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
Upvotes: 0
Views: 1320
Reputation: 903
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.
Upvotes: 1
Reputation: 111
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!
Upvotes: 0