簡體   English   中英

以編程方式編輯Web.Config-“ System.Net”部分嗎?

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

我想更改web.config中的“ system.net”部分。 我想根據運行時中的變量添加或刪除defaultProxy標記。

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

我知道,有相關的帖子正在編輯web.config,但它們都與ConnectionStringsSectionAppSettingsSection 在System.Configuration包中有關於它們的特定類,但是我沒有找到與“ system.net”相關的任何類。

您知道解決此問題的任何快捷方法嗎? 提前致謝

我找到了一種方法。 我使用以下代碼啟用或禁用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類。

建議您不要在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);
}

當然,我需要查看更多代碼以給出更完整的答案。

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM