【发布时间】:2018-03-14 16:59:19
【问题描述】:
我需要访问 web.config 文件中的 system.webServer/security/requestFiltering/requestLimits 部分,以获取属性 maxAllowedContentLength 的值。验证配置需要此值,因此用户不能设置比 web.config 文件中定义的值更高的值。要验证此配置,还需要属性 maxRequestLength (system.web/httpRuntime) 中的值,但我们已经通过以下代码获取该值:
(ConfigurationManager.GetSection("system.web/httpRuntime") as System.Web.Configuration.HttpRuntimeSection).MaxRequestLength
我已经试过了:
(ConfigurationManager.GetSection("system.webServer") as IgnoreSection).SectionInformation.GetRawXml(),但它会抛出System.InvalidOperationException。(System.Web.Configuration.WebConfigurationManager.GetSection("system.webServer") as IgnoreSection).SectionInformation.GetRawXml(),但它也会抛出一个System.InvalidOperationException。ConfigurationManager.GetSection("system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength"),但它返回null。System.Web.Configuration.WebConfigurationManager.GetSection("system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength"),但它也返回null。DiskJunky 建议的
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None),但它会抛出System.ArgumentException,并显示消息“不在独立 exe 中运行时必须指定 exePath”。
另外,我做了下面的代码:
using (System.IO.StreamReader reader = new System.IO.StreamReader(System.Web.HttpRuntime.AppDomainAppPath + "/web.config"))
{
System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
xmlDocument.LoadXml(reader.ReadToEnd());
if (xmlDocument.GetElementsByTagName("requestLimits").Count > 0)
{
var attrMaxAllowedContentLength = xmlDocument.GetElementsByTagName("requestLimits")[0].Attributes.Cast<System.Xml.XmlAttribute>().FirstOrDefault(atributo => atributo.Name.Equals("maxAllowedContentLength"));
return (Convert.ToDecimal(attrMaxAllowedContentLength.Value) / (decimal)(Math.Pow(1024, 2)));
}
//Default value of the configuration
return (decimal)28.6;
}
但我认为这不是最好的解决方案。
P.S.:我正在处理 maxRequestLength 和 maxAllowedContentLength 的值可能不同的可能性。
P.S.2.:我知道 Microsoft.Web.Administration,但我需要一个不涉及此 dll 的解决方案。
【问题讨论】:
标签: c# asp.net .net webforms web-config