如何在运行时更改HttpRuntime设置(例如WaitChangeNotification)?

时间:2011-05-11 04:02:22

标签: c# asp.net web-config

通过在xml文件中键入设置,可以轻松地在web.config中设置设置。但是,我想在运行时设置一些设置。

具体来说,我想设置system.web / httpRuntime / WaitChangeNotification设置。

我已经尝试过了,但它会抛出一个错误,表示配置是只读的。

var section = HttpContext.Current.GetSection("system.web/httpRuntime") as System.Web.Configuration.HttpRuntimeSection;
section.WaitChangeNotification = 6;

2 个答案:

答案 0 :(得分:1)

编辑配置文件有不同的API。简而言之,您可以使用WebConfigurationManager打开配置文件以获取Configuration对象,对其进行修改,然后使用Save方法之一来保存文件。

有关详细信息,请参阅MSDN中的Editing ASP.NET Configuration Files。另请注意,修改配置文件会重新启动应用程序。

答案 1 :(得分:1)

这不是一个好主意,但这完全可以使用反射。

以下是将Soap扩展注入app config的Web服务部分的代码示例:

// Turn the read only field non-readonly
WebServicesSection wss = WebServicesSection.Current;
SoapExtensionTypeElement e = new SoapExtensionTypeElement(typeof (TraceExtension), 1, PriorityGroup.High);

FieldInfo readOnlyField = typeof(System.Configuration.ConfigurationElementCollection).GetField("bReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
readOnlyField.SetValue(wss.SoapExtensionTypes, false);

// Bind to web services section of config
wss.SoapExtensionTypes.Add(e);

// Restore the original so other things don't break
MethodInfo resetMethod = typeof(System.Configuration.ConfigurationElementCollection).GetMethod("ResetModified", BindingFlags.NonPublic | BindingFlags.Instance);
resetMethod.Invoke(wss.SoapExtensionTypes, null);

MethodInfo setReadOnlyMethod = typeof(System.Configuration.ConfigurationElementCollection).GetMethod("SetReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
setReadOnlyMethod.Invoke(wss.SoapExtensionTypes, null);

显然这不是 retrospective 所以它只会影响完成后从配置中拉出的值。

...再一次,你可能不会想要来做这件事,但这是可能的。

相关问题